How can I programmatically change the selected item in a UITabBar?
Asked
Active
Viewed 1.8k times
2 Answers
42
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
-
I get this error: Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Directly modifying a tab bar managed by a tab bar controller is not allowed.' – Zia Jul 09 '15 at 23:29
-
Is the `UITabBar` owned by a `UITabBarController`? And, if so, can you obtain a reference to it? – ndmeiri Jul 09 '15 at 23:31
-
-
Thanks! That worked. Can you please modify your answer to: selectedViewController = viewControllers![newIndex] as UIViewController – Zia Jul 09 '15 at 23:53
-
1Great! I'm glad I could help. I modified my answer. I updated it to use the forced downcast operator `as!`, which is Swift 2 syntax. – ndmeiri Jul 10 '15 at 00:00
1
Swift 5 and Later
class YOUR_TABBAR_CONTROLLER: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
self.selectedIndex = 0 (or any other existing index)
}
}

asilturk
- 198
- 1
- 7