简体   繁体   English

iOS动态更改UINavigationBar的背景图片

[英]iOS Dynamic Change UINavigationBar's Background With Image

I have read this and change UINavigationBar's background: 我已阅读此内容并更改了UINavigationBar的背景:

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

you see, I add a image named top-with-logo.png , and I want to change the background view by adding an image named top-without-logo.png . 您会看到,我添加了一个名为top-with-logo.png的图像,并且我想通过添加一个名为top-without-logo.png的图像来更改背景视图。 But the code above will change the background forever and i cannont change any more. 但是上面的代码将永远改变背景,我再也不能改变了。 Do you know how? 你知不知道怎么?

Thank you very much. 非常感谢你。

I'm not sure I understand what you mean, but you can place a Boolean ivar on your app's delegate. 我不确定我理解您的意思,但是您可以在应用程序的委托中放置一个布尔型ivar。 then in the function you load top-with-logo.png if it's true/false and load top-without-logo.png if it's the other value. 然后在函数中加载top-with-logo.png(如果是true / false),并加载top-without-logo.png(如果它是其他值)。 then, when you want to change the logo, just change the Boolean's value and call setNeedsDisplay on the navigationBar. 然后,当您想更改徽标时,只需更改布尔值,然后在navigationBar上调用setNeedsDisplay。

if you use xib files, you can also subclass UINavigationBar, and instead of using a catagory you override the drawRect function and place the variable as an instance variable as a subclass, I believe it is cleaner, but you can only set that up in Interface builder ( otherwise there's no way to tell a UINavigationController to use a different class for the navigationBar property ) 如果使用xib文件,则还可以继承UINavigationBar的子类,而不是使用类别,而是重写drawRect函数并将该变量作为实例变量作为子类放置,我相信它会更干净,但是只能在Interface中进行设置生成器(否则无法告诉UINavigationController为navigationBar属性使用其他类)

You can use, 您可以使用,

UINavigationBar *navigationBar = self.navigationController.navigationBar;
UIImage *image = [UIImage imageNamed: @"NavBar-Wood.png"];
[navigationBar setBackgroundImage:image forBarMetrics: UIBarMetricsDefault];
self.navigationController.navigationBar.tintColor = [UIColor brownColor];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM