Search code examples
iosswiftuitabbarcontrollerselectedindex

Cannot select specific Tab Index to show in Tab Bar Controller, always shows 0th index


I have a tab bar controller with four tabs. I want to show the first item at the beginning. With a button click from the first item (view), when it is clicked, I want to show the second tab. How can I do that?

I created a custom tabbarController class and tried to give tabbarindex like below. I checked at the beginning without a button click but it didn't work. It always loads the first tab bar item.

class HTabViewController: UITabBarController, UITabBarControllerDelegate {
    var controllerArray : [UIViewController] = []

    override func viewDidLoad() {
        super.viewDidLoad()
        self.tabBarController?.selectedIndex = 2
        self.tabBar.tintColor = UIColor.red
       // defineViewController()
    }
}

Note : can we show specific tab item with a button click?


Solution

  • Since self is the UITabBarController, you need to set the selectedIndex on self, not self.tabBarController.

    override func viewDidLoad() {
        super.viewDidLoad()
    
        selectedIndex = 2
        tabBar.tintColor = UIColor.red
    }