更改UINavigationBar背景图像 [英] Changing the UINavigationBar background image
问题描述
我一直在尝试更改应用程序的UINavigationBar的背景图像。我尝试了几种方法。首先,我在AppDelegate类中添加了以下代码:
I've been trying to change the background image of the UINavigationBar of my application. I tried several ways. First I added to my AppDelegate class the following code:
@implementation UINavigationBar (CustomImage)
- (void)drawRect:(CGRect)rect {
UIImage *image = [UIImage imageNamed: @"navigationbar.png"];
[image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
}
@end
但它无效。我的下一个尝试是编写一个CustomizedNavigationBar类,它覆盖了 drawRect 方法。看起来像这样:
But it wasn't working. My next try was to write a CustomizedNavigationBar Class which is overriding the drawRect method. It looked like that:
CustomizedNavigationBar.h
#import <UIKit/UIKit.h>
@interface CustomizedNavigationBar : UINavigationBar
@end
CustomizedNavigationBar.m
#import "CustomizedNavigationBar.h"
@implementation CustomizedNavigationBar
- (void) drawRect:(CGRect)rect {
UIImage *image = [UIImage imageNamed: @"navigationbar.png"];
[image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
NSLog(@"I got called!!!!!");
}
@end
在我的.xib文件中定义NavigationBar我将类更改为新的CustomizedNavigationBar。但它仍然没有用..
In my .xib file where the NavigationBar is defined I changed the class to the new CustomizedNavigationBar. But still it is not working..
作为另一个测试我下载了一个示例项目,其中应该更改背景图像。但即使使用该示例代码也无法正常工作。
As another test I downloaded an example project where the background image should be changed. But even with that sample code it was not working.
我做错了什么?我正在使用IOS 5.我可以定义背景图像的任何建议或其他方式吗?
What am I doing wrong? I am using IOS 5. Any suggestions or other ways I could define a background image?
感谢您的回答!
推荐答案
从iOS 5开始,你应该使用 setBackgroundImage:forBarMetrics:
method:
Starting in iOS 5 you should use the setBackgroundImage:forBarMetrics:
method:
[myNavbar setBackgroundImage:[UIImage imageNamed: @"UINavigationBarBackground.png"]
forBarMetrics:UIBarMetricsDefault];
并且在 Swift :
navigationBar.setBackgroundImage(UIImage(named: "UINavigationBarBackground.png"),
forBarMetrics: .Default)
这篇关于更改UINavigationBar背景图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!