自定义UITabBar背景图像不能在iOS 5及更高版本中使用

我有一个简单的一段代码,在tabBar上放置一个背景图像。

UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"tabBG.png"]]; [self.tabBarController.tabBar insertSubview:imageView atIndex:0]; [imageView release]; 

这在iOS 4中工作正常,但在iOS 5中testing时,它不起作用。

我正在尝试执行以下操作:

 UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"tabBG.png"]]; NSString *reqSysVer = @"4.3"; NSString *iOSVersion = [[UIDevice currentDevice] systemVersion]; if ([iOSVersion compare:reqSysVer options:NSNumericSearch] !=NSOrderedDescending) { // code for iOS 4.3 or below [self.tabBarController.tabBar insertSubView:imageView atIndex:0]; } else { // code for iOS 5 [self.tabBarController.tabBar insertSubView:imageView atIndex:1]; } [imageView release]; 

唉,这不工作…任何人都可以提供一个解决scheme?

iOS5提供了UIAppearance Proxy。

另外,最好的做法是根据能力切换你的代码(在这种情况下它是respondsToSelector),而不是iOS版本 – 这是一个脆弱的假设(谁来说它将来不会改变)。

您可以为该实例或全局的所有选项卡栏设置它:

 // not supported on iOS4 UITabBar *tabBar = [tabController tabBar]; if ([tabBar respondsToSelector:@selector(setBackgroundImage:)]) { // set it just for this instance [tabBar setBackgroundImage:[UIImage imageNamed:@"tabbar_brn.jpg"]]; // set for all // [[UITabBar appearance] setBackgroundImage: ... } else { // ios 4 code here } 
 //---- For providing background image to tabbar UITabBar *tabBar = [tabBarController tabBar]; if ([tabBar respondsToSelector:@selector(setBackgroundImage:)]) { // ios 5 code here [tabBar setBackgroundImage:[UIImage imageNamed:@"PB_MD_footer_navBg_v2.png"]]; } else { // ios 4 code here CGRect frame = CGRectMake(0, 0, 480, 49); UIView *tabbg_view = [[UIView alloc] initWithFrame:frame]; UIImage *tabbag_image = [UIImage imageNamed:@"PB_MD_footer_navBg_v2.png"]; UIColor *tabbg_color = [[UIColor alloc] initWithPatternImage:tabbag_image]; tabbg_view.backgroundColor = tabbg_color; [tabBar insertSubview:tabbg_view atIndex:0]; } 

审查了各种文章后,我find了答案,任何人都有同样的问题:

 UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"tabBG.png"]]; if ([[[UIDevice currentDevice] systemVersion] floatValue] > 4.9) { //iOS 5 [self.tabBarController.tabBar insertSubview:imageView atIndex:1]; } else { //iOS 4.whatever and below [self.tabBarController.tabBar insertSubview:imageView atIndex:0]; } [imageView release]; 

奇迹般有效! 请享用。

我意识到这个问题已经解决了,我把这个post发给了和我一样有问题的人。 我想将一个背景图像添加到选项卡中的选定选项卡。 这是解决scheme:

 [[UITabBar appearance] setBackgroundImage:[UIImage imageNamed:@"tabbar.png"]]; [[UITabBar appearance] setSelectionIndicatorImage:[UIImage imageNamed:@"tabbar-item.png"]]; 

第二行在这里添加一个背景图片到选中的选项卡中。

iOS 5 forBarMetrics:UIBarMetricsDefault有一些新forBarMetrics:UIBarMetricsDefault

这是关于这个的苹果文件

[[UINavigationBar appearance] setBackgroundImage:toolBarIMG forBarMetrics:UIBarMetricsDefault];