专业java、php、iOS、C++、网页设计、平面设计、网络营销、游戏开发、前端与移动开发培训机构
代码搭建项目主框架(抽取)
在
HMMainTabbarViewController
里面添加class HMMainTabbarController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() // 添加4个子控制器 addChildViewControllers() } /// 添加4个子控制器 private func addChildViewControllers() { // 设置barBar的TintColor tabBar.tintColor = UIColor.orange // 首页 let homeTableVC = HMHomeViewController() addChildViewController(controller: homeTableVC, title: "首页", imageName: "tabbar_home") // 消息 let messageTableVC = HMMessageViewController() addChildViewController(controller: messageTableVC, title: "消息", imageName: "tabbar_message_center") // 发现 let discoverTableVC = HMDiscoveryViewController() addChildViewController(controller: discoverTableVC, title: "发现", imageName: "tabbar_discover") // 我 let profileTableVC = HMProfileViewController() addChildViewController(controller: profileTableVC, title: "我", imageName: "tabbar_profile") } /// 添加tabBar子控制器 private func addChildViewController(controller: UIViewController, title: String, imageName: String) { controller.title = title controller.tabBarItem.image = UIImage(named: imageName) let profileNav = UINavigationController(rootViewController: controller) addChildViewController(profileNav) } }
发现tabBarItem图片和文字选中时的颜色不对,不是我们想要的,解决方法:
1.我们发下它默认就是蓝色的,那是因为系统进行了渲染,需要修改图片的渲染模式:
/// 添加tabBar子控制器 private func addChildViewController(controller: UIViewController, title: String, imageName: String) { controller.title = title controller.tabBarItem.image = UIImage(named: imageName) // 设置选中图片 let selectedImageName = imageName + "_selected" controller.tabBarItem.selectedImage = UIImage(named: selectedImageName)?.withRenderingMode(UIImageRenderingMode.alwaysOriginal) // 设置选中文字 controller.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.orange], for: UIControlState.selected) let profileNav = UINavigationController(rootViewController: controller) addChildViewController(profileNav) }
- 2.设置barBar的TintColor,适合图片颜色和字体颜色一样的情况
// 设置barBar的TintColor tabBar.tintColor = UIColor.orangeColor()
为什么要自定义UITabBarController
- 想把UITabBarController内部的子控制器细节屏蔽起来,不让外界了解
- 每一段代码都应该放在最合适的地方
重复代码的抽取
- 相同的代码放到一个方法中
- 不同的东西变成参数
- 在需要用到这段代码的地方传递参数、调用方法