专业java、php、iOS、C++、网页设计、平面设计、网络营销、游戏开发、前端与移动开发培训机构
添加 iPhone
界面中 tabbar controller
的 子控制器
在
CZTabBarController
的viewDidLoad
中添加tabbar controller
的子控制器
- (void)viewDidLoad { [super viewDidLoad]; // 添加动态控制器 CZHomeViewController *home = [[CZHomeViewController alloc] init]; home.title = @"动态"; home.tabBarItem.image = [UIImage imageNamed:@"tabbar_icon_auth"]; [self addChildViewController:home]; // 添加与我相关控制器 CZAboutMeViewController *aboutMe = [[CZAboutMeViewController alloc] init]; aboutMe.title = @"与我相关"; aboutMe.tabBarItem.image = [UIImage imageNamed:@"tabbar_icon_at"]; [self addChildViewController:aboutMe]; // 添加我的空间控制器 CZAboutMeViewController *zone = [[CZAboutMeViewController alloc] init]; zone.title = @"我的空间"; zone.tabBarItem.image = [UIImage imageNamed:@"tabbar_icon_space"]; [self addChildViewController:zone]; // 添加发现控制器 CZAboutMeViewController *more = [[CZAboutMeViewController alloc] init]; more.title = @"发现"; more.tabBarItem.image = [UIImage imageNamed:@"tabbar_icon_more"]; [self addChildViewController:more]; }
- 运行效果如下:
发现
viewDidLoad
里面有很多重复的代码,可以抽取到一个方法里面/** * 添加tabbar view controller 的子控制器 * @param controller 子控制器 * @param title 子控制器的标题 * @param imageName 子控制器的图片名称 */ - (void)addChildViewController:(UIViewController *)controller title:(NSString *)title imageName:(NSString *)imageName { // 设置 controller.title = title; controller.tabBarItem.image = [UIImage imageNamed:imageName]; // 添加动态控制器 [self addChildViewController:controller]; }
修改
viewDidLoad
里添加子控制器的代码- (void)viewDidLoad { [super viewDidLoad]; // 添加动态控制器 [self addChildViewController:[[CZHomeViewController alloc] init] title:@"动态" imageName:@"tabbar_icon_auth"]; // 添加与我相关控制器 [self addChildViewController:[[CZAboutMeViewController alloc] init] title:@"与我相关" imageName:@"tabbar_icon_at"]; // 添加我的空间控制器 [self addChildViewController:[[CZAboutMeViewController alloc] init] title:@"我的空间" imageName:@"tabbar_icon_space"]; // 添加发现控制器 [self addChildViewController:[[CZAboutMeViewController alloc] init] title:@"发现" imageName:@"tabbar_icon_more"]; }
发现
tabBar
选中时的图片和文字颜色
不是想要的效果,设置tabBarItem
高亮时的图片和文字颜色/** * 添加tabbar view controller 的子控制器 * @param controller 子控制器 * @param title 子控制器的标题 * @param imageName 子控制器的图片名称 */ - (void)addChildViewController:(UIViewController *)controller title:(NSString *)title imageName:(NSString *)imageName { // 设置 controller.title = title; controller.tabBarItem.image = [UIImage imageNamed:imageName]; // 拼接高亮图片的名称 NSString *selectedImageName = [NSString stringWithFormat:@"%@_click", imageName]; // 设置高亮图片, 并且图片不需要系统的渲染,使用图片本身的颜色 controller.tabBarItem.selectedImage = [[UIImage imageNamed:selectedImageName] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]; // 设置高亮时的文字颜色 [controller.tabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor lightGrayColor]} forState:UIControlStateSelected]; // 添加动态控制器 [self addChildViewController:controller]; }