UITabBarController *tabBarController = [[UITabBarController alloc] init]; // 獲取選項卡控制器視圖的全部子視圖,保存到一數組中 NSArray *array = [tabBarController.view subviews]; // 索引值爲1的應該就是TabBar UITabBar *tabBar = [array objectAtIndex:1]; // UIImage *image = [UIImage imageNamed:@"tabbarbg.png"]; UIImage *image = [UIImage imageWithContentsOfFile:sourcePath]; tabBar.layer.contents = (id)image.CGImage;
或者:數組
tabBarController = [[UITabBarController alloc] init]; [tabBarController setViewControllers: view_manager]; UIImageView *tab_imgv = [UIImageView alloc] initWithImage:[UIImage imageNamed:@"tabbar_bg.png"]]; tab_imgv.frame = CGRectMake(0,0,320,49); tab_imgv.contentMode = UIViewContentModeScaleToFill; // 爲何atIndex是1,看SDK [[tabBarController tabBar] insertSubview:tab_imgv atIndex:1]; [tab_imgv release]; [view_manager release];
或者:app
UITabBarController *tabBarController = [[UITabBarController alloc] init]; // 初始化一矩形視圖框架 CGRect frame = CGRectMake(0,0,320,49); UIView *v = [[UIView alloc] initWithFrame:frame]; // 以圖片爲平鋪的顏色模板,初始化顏色 UIImage *img = [UIImage imageNamed:@"tabbarbg.png"]; UIColor *color = [[UIColor alloc] initWithPatternImage:img]; // 設置視圖背景色 v.backgroundColor = color; // 將視圖插入到選項卡欄底層 [tabBarController.tabBar insertSubview:v atIndex:0]; tabBarController.tabBar.opaque = YES; [color release]; [v release];
或者:在UITabBarController子類中重寫init方法來初始化框架
- (id)init { if(self=[super init]){ //方法一 UIImageView *imgv = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"tabbarbg.png"]]; imgv.frame = CGRectMake(0,0,self.tabBar.frame.size.width,self.tabBar.frame.size.height); imgv.contentMode = UIViewContentModeScaleToFill; // imgv.frame = CGRectOffset(imgv.frame,0,1); [[self tabBar] insertSubview:imgv atIndex:0]; [imgv release]; // 方法二 CGRect frame = CGRectMake(0,0,self.view.bounds.size.width,49); UIView *view = [[UIView alloc] initWithFrame:frame]; UIImage *tabImage = [UIImage imageNamed:@"tabbg.png"]; UIColor *color = [[UIColor alloc] initWithPatternImage:tabImage]; [view setBackgroundColor:color]; [color release]; [[self tabBar] insertSubview:view atIndex:0]; [view release]; } }
固然在iOS5開始就最方便了,在iOS5中提供了一個API來設置UITabBar的背景圖片,以及表示選中的圖片。ide
UIImage *tabBackground = [[UIImage imageNamed:@"tab_bg.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0)]; [[UITabBar appearance] setBackgroundImage:tabBackground]; [[UITabBar appearance] setSelectionIndicatorImage:[UIImage imageNamed:@"tab_select_indicator.png"]];
- (void)hideExsitingTabBar { for(UIView *view in self.view.subviews) { if([view isKindOfClass:[UITabBar class]]) { view.hidden = YES; break; } } }
nextViewController.hidesBottomBarWhenPushed = YES; [self.navigationController pushViewController:nextViewController animated:NO];