Change UITabBar selectedItem in Swift

风格不统一 提交于 2019-12-22 04:33:21

问题


How can I programmatically change the selected item in a UITabBar?


回答1:


Swift 3 and later

As of Swift 3, you can also use

tabBarController.selectedIndex = 0 // (or any other existing index)

(Thank you, @nidomiro.)


Swift 2.2 and earlier

Try the following

tabBar.selectedItem = tabBar.items![newIndex] as! UITabBarItem

Assuming you have access to the UITabBarController that owns the UITabBar, you can do the following

self.selectedViewController = self.viewControllers![newIndex] as! UIViewController

The above line of code should be put somewhere inside of the UITabBarController subclass.

But if you have access to the tab bar controller from "outside," do the following

tabBarController.selectedViewController = tabBarController.viewControllers![newIndex] as! UIViewController



回答2:


Swift 5 and Later

class YOUR_TABBAR_CONTROLLER: UITabBarController {    

  override func viewDidLoad() {
  super.viewDidLoad()

  self.selectedIndex = 0 (or any other existing index)

  }
}


来源:https://stackoverflow.com/questions/31329680/change-uitabbar-selecteditem-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!