问题: 改背景仅需在UINavigationBar的子视图中加入UIImageView,但如果想在应用中修改背景又应该怎么办呢?
解决: 有些第三方的框架或者类都要派生UINavigationBar,它们有些“坏味道”!
绝妙解决: 我们会创建一个UINavigationBar的类别,并在UIApplicationDelegate中创建一个UIImage属性。
AppDelegate.h
@interface AppDelegate : NSObject { UIImage *navImage; //其他略 }
@property (nonatomic, retain) UIImage *navImage; //其他略
AppDelegate.m
@implementation AppDelegate;
@synthesize navImage; //其他略
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions: (NSDictionary *)launchOptions { self.navImage = [UIImage p_w_picpathNamed:@"navigation-bar-cooler.png"]; //其他略
return YES; }
UINavigationBar (Helpers).h
@interface UINavigationBar (Helpers)
@end
UINavigationBar (Helpers).m
#import "AppDelegate.h"
#import "UINavigationBar (Helpers).h"
@implementation UINavigationBar (Helpers)
- (void)drawRect:(CGRect)rect { AppDelegate *delegate = (AppDelegate *) [[UIApplication sharedApplication] delegate]; [delegate.navImage drawInRect: CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)]; }
@end
一旦完成了这些,就可以按如下代码改变UINavigationBar的背景了:
- (void)viewWillAppear:(BOOL)animated { delegate.navImage = [UIImage p_w_picpathNamed: @"navigation-bar-other.png"]; [self.navigationController.navigationBar setNeedsDisplay];
[super viewWillAppear:animated]; }