简体   繁体   中英

Navigate to a certain tab on a UITabBarController

In an objective-C Xcode project, I have currently set 5 different ViewControllers to 5 different tabs on a tab bar (a, b, c, d, e). Whenever I try to navigate back to this tab bar controller from a view in my app other than ae, I can only navigate to the "a" view of the TabBarVC (the first view). How can I navigate to say the c view of this tab bar from a different view?

You should navigate to TabBarVC passing parameter initialIndex telling which tab should be presented. Then override viewWillAppear(_:) method and set selectedIndex to initialIndex ( 0..<numberOfControllers ) to set initially selected tab.

class TabBarVC: UITabBarController {

    ...

    var initialIndex: Int?

    ...

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        if let initialIndex = initialIndex, let count = self.viewControllers?.count, initialIndex < count {
            self.initialIndex = nil
            self.selectedIndex = initialIndex
        }
    }
}

If you are using segue, this can be done in source controller in:

override func prepare(for segue: UIStoryboardSegue, sender: Any?)

Otherwise, just set initialIndex before presenting controller.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM