Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set the default tab for tab bar controller in swift

I'm new to Swift, and about a 5 out of 10 on the Objective-C knowledge scale..

I created a basic three tab Swift application. Each tab has an associated swift class file, e.g. FirstViewController.swift , SecondViewController.swift, ThirdViewController.swift.

When I select the third tab, I now open the application preference settings using a viewDidAppear function override in ThirdViewController.swift, e.g.:

override func viewDidAppear(animated: Bool) {
    // open app preference s
    if let url = NSURL(string:UIApplicationOpenSettingsURLString) {
        UIApplication.sharedApplication().openURL(url)
    }
}

Though, prior to opening the preferences, I would like to set the active tab back to the first tab. How is this done elegantly in Swift.

The following does not work:

self.tabBarController.selectedIndex = 0

As the UIViewController of the ThirdViewController class does not have a tabBarController.

Brian.

like image 489
kauai Avatar asked Oct 20 '14 05:10

kauai


People also ask

How do I add more tabs to my tab bar controller?

To add a tab, first drag a new View Controller object to the storybard. Next control-drag from the tab bar controller to new view controller and select view controllers under Relationship Segue . Your tab bar controller will update with a new tab.


1 Answers

User Omkar responded above with the correct answer. I can successfully switch the first tab using the following viewDidAppear in ThirdViewController.swft

override func viewDidAppear(animated: Bool) {         
    self.tabBarController?.selectedIndex = 0     
}
like image 157
kauai Avatar answered Nov 04 '22 05:11

kauai