Zia
Zia

Reputation: 14722

Change UITabBar selectedItem in Swift

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

Upvotes: 9

Views: 17888

Answers (2)

ndmeiri
ndmeiri

Reputation: 5039

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

Upvotes: 43

asilturk
asilturk

Reputation: 218

Swift 5 and Later

class YOUR_TABBAR_CONTROLLER: UITabBarController {    

  override func viewDidLoad() {
  super.viewDidLoad()

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

  }
}

Upvotes: 1

Related Questions