I need write some code to switch the view to another tab when the iOS app starts (so, for example, the second tab is shown by default rather than the first).
I'm new to Swift, and have worked out the following:
The code should probably go in the override func viewDidLoad() function of the ViewController of the first tab.
The following code shows the second ViewController, but not with the tab bar at the bottom (vcOptions is the second ViewController tab item:
let vc : AnyObject! = self.storyboard.instantiateViewControllerWithIdentifier("vcOptions")
self.showViewController(vc as UIViewController, sender: vc)
I think the answer may lie in using the UITabbarController.selectedIndex = 1, but not quite sure how to implement this.
Swift 3
You can add this code to the default view controller (
index 0
) in your tabBarController:Upon load, this would automatically move the tab to the second item in the list, but also allow the user to manually go back to that view at any time.
To expand on @codester's answer, you don't need to check and then assign, you can do it in one step:
The viewController has to be a child of UITabBarControllerDelegate. So you just need to add the following code on SWIFT 3
In a typical application there is a UITabBarController and it embeds 3 or more UIViewController as its tabs. In such a case if you subclassed a UITabBarController as YourTabBarController then you can set the selected index simply by:
In case you are navigating to YourTabBarController from any other view, then in that view controller's prepare(for segue:) method you can do:
I am using this way of setting tab with Xcode 10 and Swift 4.2.
1.Create a new class which supers UITabBarController. E.g:
2.Add the following code to the function viewDidLoad():
3.Go to storyboard, and set the Custom Class of your Tab Bar Controller to this new class. (MyVotes1 as the example in the pic)
If your
window
rootViewController
isUITabbarController
(which is in most cases) then you can accesstabbar
indidFinishLaunchingWithOptions
in theAppDelegate
file.This will open the tab with the
index
given (1) inselectedIndex
.If you do this in
viewDidLoad
of yourfirstViewController
, you need to manage by flag or another way to keep track of the selected tab. The best place to do this indidFinishLaunchingWithOptions
of yourAppDelegate
file orrootViewController
custom classviewDidLoad
.