I have a swift app and on my UIViewController I have a button. In my StoryBoard
I attached the button to the UITabController
and now when user clicks it - he gets redirected to it. But, by default, he is presented with the 1st tab. Is there a way of showing the 3rd tab instead?
This is the option of my segue:
Yes - but how complex it needs to be depends on what you're doing.
If you only ever go from the first UIViewController
then you can simply add some code to the viewWillAppear
or viewWillLoad
function (remembering the index is zero-based)
override func viewWillAppear(animated: Bool)
{
self.selectedIndex = 2
}
If you have more than one entry point, you can use the prepareForSegue
to set a flag in the tabBarController
. In this example, I have two buttons on the UIViewController
with tag
values set as 100, and 200
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "TabBarSegue"
{
if let destinationVC = segue.destinationViewController as? myTabBarViewController
{
if sender!.tag == 100
{
destinationVC.jumpToTab2 = true
}
if sender!.tag == 200
{
destinationVC.jumpToTab2 = false
}
}
}
}
and then in the TabBarController
, I have defined a flag jumpToTab2
class myTabBarViewController: UITabBarController
{
var jumpToTab2 : Bool = false
override func viewWillAppear(animated: Bool)
{
if jumpToTab2
{
self.selectedIndex = 2
}
jumpToTab2 = false // reset the flag before next time
}
}