这里用代码实现Tab切换,修改tab的不同状态的图片及文字效果。
1.建立OC文件,来自父类UITabBarController
2.这个UITabBarController要怎么用呢,它有方法将ViewController作为子布局加进来
//设置tab bar item字体及图片 着色;这里设置了文字及图片会有红色的选择效果;默认白色
[self.tabBar setTintColor:[UIColor redColor]];
//“首页”Tab
UIViewController *tabOne = [[UIViewController alloc] init];//定义视图
[tabOne.tabBarItem setTitle:@"首页"]; //标题
[tabOne.tabBarItem setImage:[UIImage imageNamed:@"ic_home"]]; //item 图片
[tabOne.tabBarItem setBadgeValue:@"123"]; //设置徽章,数字
[tabOne.view setBackgroundColor:[UIColor redColor]];//视图背景色
//”添加“Tab
UIViewController *tabTwo = [[UIViewController alloc] init];
[tabTwo.tabBarItem setTitle:@"添加"];
[tabTwo.tabBarItem setImage:[UIImage imageNamed:@"ic_add"]];
[tabTwo.view setBackgroundColor:[UIColor greenColor]];
//“设置”Tab
UIViewController *tabThree = [[UIViewController alloc] init];
[tabThree.tabBarItem setTitle:@"设置"];
[tabThree.view setBackgroundColor:[UIColor blueColor]];
[tabThree.tabBarItem setImage:[UIImage imageNamed:@"ic_setting"]];
//第一种:一个一个添加方式
[self addChildViewController:tabOne];
[self addChildViewController:tabTwo];
[self addChildViewController:tabThree];
//第二种:多种添加方式
self.viewControllers = @[tabOne,tabTwo,tabThree];
图片来自:https://design.google.com/icons/ (PS:要翻墙)
效果图:
3.有时我们想添加状态图片或文字,选中时是另外的图片或文字颜色
(1).对于图片
//选择时的图片
UIImage *selectedImg =[UIImage imageNamed:@"ic_setting_selected"];
[tabThree.tabBarItem setSelectedImage:[selectedImg imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];//设置选中时的颜色,设置为UIImageRenderingModeAlwaysOriginal,保留原始图片,取消tint color
ImageWithRenderingMode有三种状态:默认第一种
1. UIImageRenderingModeAutomatic // 根据图片的使用环境和所处的绘图上下文自动调整渲染模式。
2. UIImageRenderingModeAlwaysOriginal // 始终绘制图片原始状态,不使用Tint Color。
3. UIImageRenderingModeAlwaysTemplate // 始终根据Tint Color绘制图片,忽略图片的颜色信息。
(2).对于文字
//正常时的颜色
NSMutableDictionary *normalTextAttrs = [NSMutableDictionary dictionary];
normalTextAttrs[NSForegroundColorAttributeName]=[UIColor blackColor]; //黑色效果
//选择时的颜色
NSMutableDictionary *selectedTextAttrs = [NSMutableDictionary dictionary];
selectedTextAttrs[NSForegroundColorAttributeName]=[UIColor blueColor]; //绿色效果
//添加文字颜色
[tabThree.tabBarItem setTitleTextAttributes:normalTextAttrs forState:UIControlStateNormal];
[tabThree.tabBarItem setTitleTextAttributes:selectedTextAttrs forState:UIControlStateSelected];
效果图: