Setting default tab in UITabBar in swift

If you're using UISegue from UIStoryBoard, you can use this in UIViewController where you're performing UISegue

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let tabBarController = segue.destination as? UITabBarController
    tabBarController?.selectedIndex = 1
}

or

class TabBarController: UITabBarController {

   override func viewDidLoad() {
       super.viewDidLoad()
       self.selectedIndex = 1
   }

}

this code in your UITabBarController itself.


There is a nice way to do this straight from interface builder on your tab bar controller click the identity inspector, and set a User Defined Runtime Attribute.

In this case each index of the tab bar control is indexed like a 0 based array. So the far left is 0, next to the right is 1, then 2 etc...

So in my case I wanted 'tasks' to be selected first, so you set the selectedIndex to type Number and value '1'. Refer to my attached image.

enter image description here


Just set the selectedIndex of the tabBarController. Something along these lines.

var freshLaunch = true
override func viewWillAppear(animated: Bool) {
     if freshLaunch == true {
         freshLaunch = false
         self.tabBarController.selectedIndex = 4 // 5th tab
     }
}

In the First items view controller write

tabBarController?.selectedIndex = 2//required value