How do I change the background of a UINavigationBar?

偶尔善良 提交于 2019-12-17 18:47:20

问题


I'd like to change the background of my UINavigationBar to a [UIColor colorWithImage:], but it isn't working. What am I missing?

EDIT:

Once I've created my subclass, where do I set the UINavigationController to use it?


回答1:


You can use the tintColor property to change the colour of a UINavigationBar, but to set an image as the background you'll have to provide your own UINavigationBar subclass and override the drawRect: method, for example:

- (void)drawRect:(CGRect)rect {
    // Drawing code 
    UIImage *img = [UIImage imageNamed: @"background-image.png"];
    [img drawInRect:CGRectMake(0, 
                               0, 
                               self.frame.size.width, 
                               self.frame.size.height)];
}

If you use Interface Builder to build your UI then to use the custom navigation bar, just select the UINavigationBar element in Interface Builder, open the Inspector and in the Identity tab specify your UINavigationBar subclass in the class field, like so:




回答2:


To have an image in the navigation bar, you have to draw it yourself, which actually isn't that hard. Save this as UINavigationBar+CustomBackground.m (it adds a custom category to UINavigationBar):

@implementation UINavigationBar (CustomBackground)

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

@end


来源:https://stackoverflow.com/questions/4319112/how-do-i-change-the-background-of-a-uinavigationbar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!