問題: 改背景僅需在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];
}
原文連接:
http://iphonedevblog.com/code/dynamically-change-a-uinavigationbars-background/