swift项目中,在tabbarviewcontroller文件里添加一个uinavigantioncontroller,tabbarviewcontroller的父类是UITabBarController;当点击不同的item时,实现未选中图片与选中图片的切换、未选中时与选中时的tab文字颜色更换,且能跳转到不同的viewcontroller文件,现在有5个viewcontroller,分别是X、Y、Z、M、N
时间: 2023-05-20 22:03:33 浏览: 183
swift——自定义UITabBar,UITabBarController和UINavigationController
5星 · 资源好评率100%
你可以在tabbarviewcontroller的viewDidLoad方法中添加以下代码来实现:
```
// 创建5个视图控制器
let xVC = XViewController()
let yVC = YViewController()
let zVC = ZViewController()
let mVC = MViewController()
let nVC = NViewController()
// 创建5个导航控制器,并将对应的视图控制器设置为根视图控制器
let xNav = UINavigationController(rootViewController: xVC)
let yNav = UINavigationController(rootViewController: yVC)
let zNav = UINavigationController(rootViewController: zVC)
let mNav = UINavigationController(rootViewController: mVC)
let nNav = UINavigationController(rootViewController: nVC)
// 设置未选中图片与选中图片
xNav.tabBarItem = UITabBarItem(title: "X", image: UIImage(named: "unselectedImage"), selectedImage: UIImage(named: "selectedImage"))
yNav.tabBarItem = UITabBarItem(title: "Y", image: UIImage(named: "unselectedImage"), selectedImage: UIImage(named: "selectedImage"))
zNav.tabBarItem = UITabBarItem(title: "Z", image: UIImage(named: "unselectedImage"), selectedImage: UIImage(named: "selectedImage"))
mNav.tabBarItem = UITabBarItem(title: "M", image: UIImage(named: "unselectedImage"), selectedImage: UIImage(named: "selectedImage"))
nNav.tabBarItem = UITabBarItem(title: "N", image: UIImage(named: "unselectedImage"), selectedImage: UIImage(named: "selectedImage"))
// 设置未选中时与选中时的tab文字颜色更换
UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.gray], for: .normal)
UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.blue], for: .selected)
// 将5个导航控制器添加到tabbarviewcontroller中
self.viewControllers = [xNav, yNav, zNav, mNav, nNav]
```
这样就可以实现在tabbarviewcontroller文件里添加一个uinavigantioncontroller,点击不同的item时,实现未选中图片与选中图片的切换、未选中时与选中时的tab文字颜色更换,且能跳转到不同的viewcontroller文件。
阅读全文