- (void)viewDidLoad {
[super viewDidLoad];
//创建TAB的VC
UIViewController* vc1 = [[UIViewController alloc] init];
homeVC.view.backgroundColor = [UIColor yellowColor];
UIViewController* vc2 = [[UIViewController alloc] init];
canteenVC.view.backgroundColor = [UIColor orangeColor];
UIViewController* vc3 = [[UIViewController alloc] init];
cartVC.view.backgroundColor = [UIColor redColor];
UIViewController* vc4 = [[UIViewController alloc] init];
mineVC.view.backgroundColor = [UIColor orangeColor];
self.viewControllers = @[
[self setTabBarVC:@"首页" image:@"h" selImage:@"h_selected" vc:vc1],
[self setTabBarVC:@"关注" image:@"s" selImage:@"s_canteen_selected" vc:vc2],
[self setTabBarVC:@"收藏" image:@"c" selImage:@"c_selected" vc:vc3],
[self setTabBarVC:@"我的" image:@"me" selImage:@"me_selected" vc:vc4]
];
}
/// 创建TAB的VC
/// @param title 标题
/// @param image 非选择状态的图片
/// @param selImage 选择状态的图片
/// @param vc 展示的VC
-(UIViewController*)setTabBarVC:(NSString*)title image:(NSString*)image
selImage:(NSString*)selImage vc:(UIViewController*)vc{
//普通状态的图片
UIImage* normalImage = [UIImage imageNamed:image];
//选中状态的图片
UIImage* selectImage = [UIImage imageNamed:selImage];
//设置文字
vc.tabBarItem = [[UITabBarItem alloc] initWithTitle:title image:normalImage selectedImage:selectImage];
//设置不同状态下文字的颜色
[vc.tabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName:UIColorFromRGB(0XDBDBDB)} forState:UIControlStateNormal];
[vc.tabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName:UIColorFromRGB(0X74C553)} forState:UIControlStateSelected];
return vc;
}
Swift版:
/// 设置页面
private func setUpUI(){
let vc1 = UIViewController()
let vc2 = UIViewController()
let vc3 = UIViewController()
let vc4 = UIViewController()
self.viewControllers = [
self.setTabBarVC(title: "首页", image: "tab_home", selectImage: "tab_home_sel", vc: vc1),
self.setTabBarVC(title: "收藏", image: "tab_s", selectImage: "tab_s_sel", vc: vc2),
self.setTabBarVC(title: "关注", image: "tab_g", selectImage: "tab_gt_sel", vc: vc3),
self.setTabBarVC(title: "我的", image: "tab_mine", selectImage: "tab_mine_sel", vc: vc4)
]
}
/// 创建TabBar控件
///
/// - Parameters:
/// - title: 标题
/// - image: 非选中状态的图片
/// - selectImage: 选中状态的图片
/// - controller: 展示的页面
private func setTabBarVC(title:String,image:String,
selectImage:String,vc:UIViewController) -> UIViewController{
//普通状态的图片
let normalImage = UIImage.init(named: image)
//选中状态的图片
let selectImage = UIImage.init(named: selectImage)
//设置文字
vc.tabBarItem = UITabBarItem.init(title: title, image: normalImage, selectedImage: selectImage)
//设置不同状态下文字的颜色
vc.tabBarItem.setTitleTextAttributes([NSAttributedString.Key.foregroundColor : UIColor.hexIntColor(0xBEBEBE)], for: .normal)
vc.tabBarItem.setTitleTextAttributes([NSAttributedString.Key.foregroundColor : UIColor.hexIntColor(0x1167BB)], for: .selected)
return vc
}