Switching to a TabBar tab view programmatically?

后端 未结 12 1950
南旧
南旧 2020-11-29 17:07

Let\'s say I have a UIButton in one tab view in my iPhone app, and I want to have it open a different tab in the tab bar of the TabBarController.

12条回答
  •  伪装坚强ぢ
    2020-11-29 17:34

    Like Stuart Clark's solution but for Swift 3:

    func setTab(_ myClass: T.Type) {
        var i: Int = 0
        if let controllers = self.tabBarController?.viewControllers {
            for controller in controllers {
                if let nav = controller as? UINavigationController, nav.topViewController is T {
                    break
                }
                i = i+1
            }
        }
        self.tabBarController?.selectedIndex = i
    }
    

    Use it like this:

    setTab(MyViewController.self)
    

    Please note that my tabController links to viewControllers behind navigationControllers. Without navigationControllers it would look like this:

    if let controller is T {
    

提交回复
热议问题