How can I switch to some tab in UITabBarController
using StoryBoard? I have tried the code below but without success (the tab is not selected):
Swift 5.3
Let tabBar
be an instance of UITabBarController
then :
tabBar.selectedViewController = tabBar.viewControllers![2]
Note:
Instead of 2, put your desired viewController's index
Here is what I do (Swift 5.x):
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
if let tabBarController = self.window?.rootViewController as? UITabBarController {
if let viewControllers: [UIViewController] = tabBarController.viewControllers {
tabBarController.selectedIndex = viewControllers.count-1
}
}
return true
}
Grab your instance of UITabBarController
then set the selectedViewController
property:
yourTabBarController.selectedViewController=[yourTabBarController.viewControllers objectAtIndex:3];//or whichever index you want
Swift 4.1
In your TabBarViewController
class, you can add this key line
self.selectedIndex = 0