我一直在尝试更改我的应用程序 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
但它不起作用.我的下一个尝试是编写一个覆盖 drawRect 方法的 CustomizedNavigationBar 类.看起来是这样的:
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
在定义 NavigationBar 的 .xib 文件中,我将类更改为新的 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:
方法:
Starting in iOS 5 you should use the -setBackgroundImage:forBarMetrics:
method:
[myNavbar setBackgroundImage:[UIImage imageNamed: @"UINavigationBarBackground.png"]
forBarMetrics:UIBarMetricsDefault];
在 Swift 4 中:
navigationBar.setBackgroundImage(UIImage(named: "UINavigationBarBackground.png"),
for: .default)
这篇关于更改 UINavigationBar 背景图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!