1. 程式人生 > >iOS tabBarItem的選中與非選中時,背景顏色,字型顏色

iOS tabBarItem的選中與非選中時,背景顏色,字型顏色

//設定tabBar的背景顏色,使用的方法

- (void)insertSubview:(UIView *)view atIndex:(NSInteger)index;

//設定tabbar的背景

UIView *tabbarBgView = [[UIViewalloc]initWithFrame:CGRectMake(0,0,self.tabBar.frame.size.width,self.tabBar.frame.size.height)];

    tabbarBgView.backgroundColor =kAppBarColor;

    [self.tabBarinsertSubview:tabbarBgView

atIndex:0];

//tabbar被選中的背景顏色

CGSize indicatorImageSize =CGSizeMake(self.tabBar.bounds.size.width/5 - 10, self.tabBar.bounds.size.height);

self.tabBar.selectionIndicatorImage = [selfdrawTabBarItemBackgroundUmageWithSize:indicatorImageSize];

    //字型大小,顏色(未被選中時)

    [[UITabBarItemappearance] setTitleTextAttributes

:[NSDictionarydictionaryWithObjectsAndKeys:kAppWhiteColor,NSForegroundColorAttributeName, [UIFontfontWithName:@"Helvetica"size:12.0f],NSFontAttributeName,nil]forState:UIControlStateNormal];

     //字型大小,顏色(被選中時)

    [[UITabBarItemappearance] setTitleTextAttributes:[NSDictionarydictionaryWithObjectsAndKeys

:kAppNavigationBarColor,NSForegroundColorAttributeName, [UIFontfontWithName:@"Helvetica"size:12.0f],NSFontAttributeName,nil]forState:UIControlStateSelected];

//繪製圖片

-(UIImage *)drawTabBarItemBackgroundUmageWithSize:(CGSize)size

{

//開始圖形上下文

UIGraphicsBeginImageContext(size);

//獲得圖形上下文

CGContextRef ctx =UIGraphicsGetCurrentContext();

CGContextSetRGBFillColor(ctx,1, 1,1, 1);

CGContextFillRect(ctx,CGRectMake(5,0, size.width, size.height));

CGRect rect =CGRectMake(0,0, size.width, size.height);

CGContextAddEllipseInRect(ctx, rect);

CGContextClip(ctx);

UIImage *image =UIGraphicsGetImageFromCurrentImageContext();

    [image drawInRect:rect];

UIGraphicsEndImageContext();

return image;

}

//tabBar和navigationBar結合使用

    UIViewController *vc = [UIViewController new];

UINavigationController *nav = [[UINavigationControlleralloc]initWithRootViewController:vc];

    vc.tabBarItem.title = @"首頁";

//設定tabbar被選中與未被選中的圖片

    nav.tabBarItem.image = [[UIImageimageNamed:@"home_btn"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];

    nav.tabBarItem.selectedImage = [[UIImageimageNamed:@"home_btn02"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];;

//設定navigationbar的顏色

    [nav.navigationBarsetBarTintColor:kAppNavigationBarColor];

//或設定navigationbar的背景圖片

[nav.navigationBar setBackgroundImage:navBarBackgroundImage forBarMetrics:UIBarMetricsDefault];