首页 文章

子类化UINavigationBar ...如何在UINavigationController中使用它?

提问于
浏览
8

我想子类化UINavigationBar(设置自定义背景图像和文本颜色)并将其用于我的应用程序中的所有导航栏 . 查看UINavigationController的API文档,看起来navigationBar是只读的:

@property(非原子,只读)UINavigationBar * navigationBar

有没有办法在我的UIViewControllers中实际使用自定义UINavigationBar?我知道其他应用程序已经完成了自定义导航栏,如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

我知道我可以使用类别来更改背景图像,但我仍然希望能够设置导航栏 Headers 的文本颜色

@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的应用程序导航栏

3 回答

  • 2

    如果你弄明白的话,我不知道 . 但对于可能有这个问题的其他人......

    您需要做的是将XIB中的类指定为您的类名(在本例中为MyNavigationBar) .

    检查WWDC 2011中的会话123 .

  • 4

    将UINavigationBar“tint”属性设置为所需的颜色 .

  • 2

    尝试创建 [UIColor colorWithPatternImage:(UIImage*)image] 并将其设置为NavBar 's backgroundColor property. I haven'尝试了这个,但我现在就会这样做 .

相关问题