Objective-C:导航栏中的背景图像和标题
-
28-09-2019 - |
题
需要背景图像和我的导航栏中的标题。对于图像,我写了一个类别:
@implementation UINavigationBar(MyNavigationBar)
- (void)setBackgroundImage {
UIImageView *aTabBarBackground = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"navBarBackgrd.png"]];
[self addSubview: aTabBarBackground];
[self sendSubviewToBack: aTabBarBackground];
[aTabBarBackground release];
}
@end
我在AppDelegate中称此类别为类别,并在整个应用程序中具有背景图像:
[navigationController.navigationBar setBackgroundImage];
每个ViewController都有一个标题:
[self setTitle:@"MyTitle"];
但是设置了背景图像后,我对标题有问题。
在第一个视图中,我看到了背景图像和标题:-),但是在下一个视图中,标题消失了。仅可见背景图像。也许标题在图像之下?
从技术上讲,这两者都可以显示。有了这个技巧,它有效:
在打开下一个ViewController之前,隐藏导航栏:
self.navigationController setNavigationbarhidden:yes];
在下一个ViewController中显示导航栏:
self.navigationController setNavigationbarhidden:no];
现在,图像和标题是可见的,但是此解决方案不是最好的;-)
解决方案
我知道了!
@implementation UINavigationBar(MyNavigationBar)
- (void)drawRect:(CGRect)rect {
UIImage *image = [UIImage imageNamed: @"navBarBackgrd.png"];
[image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
}
@end
其他提示
ios5之后,您应该这样做,例如在AppDelegate中
UIImage *img = [[UIImage imageNamed:@"image.png"]resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
[[UINavigationBar appearance] setBackgroundImage:img forBarMetrics:UIBarMetricsDefault];
[[UINavigationBar appearance] setBarStyle:UIBarStyleBlackTranslucent];
[[UINavigationBar appearance] setTintColor:[UIColor colorWithRed:0 green: 0 blue:0 alpha:1]];
不隶属于 StackOverflow