8

我想要UINavigationBar的子類(設置自定義背景圖像&文字顏色),並將其用於我的應用程序中的所有導航欄。看着爲UINavigationController的API文檔,它看起來像的導航欄爲只讀:Subclassing UINavigationBar ...我如何在UINavigationController中使用它?

@屬性(非原子,只讀)UINavigationBar的*的導航欄

有沒有實際使用自定義UINavigationBar的的方式我的UIViewControllers?我知道其他應用程序所做的自定義導航欄,如Flickr:

http://img.skitch.com/20100520-bpxjaca11h5xne5yakjdc2m6xx.png

這裏是我的UINavigationBar的子類:

#import <UIKit/UIKit.h> 

@interface MyNavigationBar : UINavigationBar <UINavigationBarDelegate> { 

} 

@end 

實施

#import "MyNavigationBar.h" 

@implementation MyNavigationBar 

- (id)initWithFrame:(CGRect)frame { 
    if (self = [super initWithFrame:frame]) { 
     // Initialization code 
    } 
    return self; 
} 

- (void)drawRect:(CGRect)rect { 
    // override the standard background with our own custom one 
    UIImage *image = [[UIImage imageNamed:@"navigation_bar_bgd.png"] retain]; 
    [image drawInRect:rect]; 
    [image release]; 
} 

#pragma mark - 
#pragma mark UINavigationDelegate Methods 

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated{ 
    // use the title of the passed in view controller 
    NSString *title = [viewController title]; 

    // create our own UILabel with custom color, text, etc 
    UILabel *titleView = [[UILabel alloc] init]; 
    [titleView setFont:[UIFont boldSystemFontOfSize:18]]; 
    [titleView setTextColor:[UIColor blackColor]]; 
    titleView.text = title; 
    titleView.backgroundColor = [UIColor clearColor]; 
    [titleView sizeToFit]; 

    viewController.navigationItem.titleView = titleView; 
    [titleView release]; 

    viewController.navigationController.navigationBar.tintColor = [UIColor colorWithRed:0.1 green:0.2 blue:0.3 alpha:0.8]; 
} 
- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated{ 
} 


- (void)dealloc { 
    [super dealloc]; 
} 

@end 

我知道我可以使用一個類別來改變背景圖像,但我仍然希望能夠設置導航欄標題的文字顏色

@implementation UINavigationBar (CustomImage) 
- (void)drawRect:(CGRect)rect { 
    UIImage *image = [UIImage imageNamed: @"navigation_bar_bgd.png"]; 
    [image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)]; 
} 
@end 

任何建議或其他解決方案?我基本上想創建一個淺色背景和深色文字,如Flickr的應用導航條

回答

2

將UINavigationBar「tint」屬性設置爲所需的顏色。

+0

這將工作改變導航欄的背景,但我想改變導航欄的默認白色文字顏色,因爲我想使用淺色的背景色,例如,如果我想使用白色背景,我需要能夠將默認的白色文本更改爲黑色 – funkadelic 2010-05-29 00:31:10

2

嘗試創建一個[UIColor colorWithPatternImage:(UIImage*)image]並將其設置爲NavBar的backgroundColor屬性。我還沒有嘗試過,但我現在就做。

4

我不知道如果你弄明白了。但對於其他人可能有這個問題...

你需要做的是指定您XIB類到你的類名(在這種情況下MyNavigationBar。

檢查會話123在WWDC 2011年

相關問題