在 Swift 中更改 UITabBar selectedItem
Change UITabBar selectedItem in Swift
如何以编程方式更改 UITabBar 中的选定项?
Swift 3 岁及以后
从 Swift 3 开始,您还可以使用
tabBarController.selectedIndex = 0 // (or any other existing index)
(谢谢@nidomiro。)
Swift 2.2 及更早版本
尝试以下方法
tabBar.selectedItem = tabBar.items![newIndex] as! UITabBarItem
假设您有权访问拥有 UITabBar
的 UITabBarController
,您可以执行以下操作
self.selectedViewController = self.viewControllers![newIndex] as! UIViewController
上面这行代码应该放在 UITabBarController
子类的某个地方。
但是如果您可以从 "outside," 访问标签栏控制器,请执行以下操作
tabBarController.selectedViewController = tabBarController.viewControllers![newIndex] as! UIViewController
Swift 5 岁及以后
class YOUR_TABBAR_CONTROLLER: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
self.selectedIndex = 0 (or any other existing index)
}
}
如何以编程方式更改 UITabBar 中的选定项?
Swift 3 岁及以后
从 Swift 3 开始,您还可以使用
tabBarController.selectedIndex = 0 // (or any other existing index)
(谢谢@nidomiro。)
Swift 2.2 及更早版本
尝试以下方法
tabBar.selectedItem = tabBar.items![newIndex] as! UITabBarItem
假设您有权访问拥有 UITabBar
的 UITabBarController
,您可以执行以下操作
self.selectedViewController = self.viewControllers![newIndex] as! UIViewController
上面这行代码应该放在 UITabBarController
子类的某个地方。
但是如果您可以从 "outside," 访问标签栏控制器,请执行以下操作
tabBarController.selectedViewController = tabBarController.viewControllers![newIndex] as! UIViewController
Swift 5 岁及以后
class YOUR_TABBAR_CONTROLLER: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
self.selectedIndex = 0 (or any other existing index)
}
}