将图像添加到UINavigationBar
问题描述:
我需要支持iOS4和iOS5。我的代码在iOS4上运行良好,但不适用于iOS5。如何解决这个问题。将图像添加到UINavigationBar
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"E_44.png"]];
imageView.frame = CGRectMake(136, 0, 52, 44);
[self.navigationController.navigationBar insertSubview:imageView atIndex:0];
[imageView release];
答
为UINavigationBar设置自定义背景以支持iOS5和iOS4!
如你所知,直到iOS 5中出来的时候,我们用drawRect
覆盖在AppDelegate
定制UINavigationBar
。 但是请知道,iOS 5为我们提供了一些新的样式设计方法(旧的方法不起作用)。
如何构建可在iOS 4和iOS 5上使用程式设计的应用程序UINavigationBar
?
你必须做到两个!
在AppDelegate
使用此代码:
@implementation UINavigationBar (UINavigationBarCategory)
- (void)drawRect:(CGRect)rect {
UIImage *img = [UIImage imageNamed:@"navbar.png"];
[img drawInRect:rect];
}
@end
,并在iOS5的viewDidLoad
方法(在你的视图实现):
if ([self.navigationController.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)]){
[self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"navbar.png"] forBarMetrics:UIBarMetricsDefault];
}
如果你看到了,这里我们问导航栏将respondToSelector到避免在iOS4上崩溃!
答
这并不增加一个背景,但是这会让你一个图像添加到导航条
// Create your image<br>
UIImage *image = [UIImage imageNamed: @"yourimage.png"];<br>
UIImageView *imageview = [[UIImageView alloc] initWithImage: image];
// set the text view to the image view<br>
self.navigationItem.titleView = imageView;
希望这有助于。