How to set default tab for tab bar controller in quick

I am new to Swift and about 5 out of 10 on the Objective-C knowledge scale.

I created a basic application with three Swift tabs. Each tab has an associated quick file file, for example. FirstViewController.swift , SecondViewController.swift , ThirdViewController.swift .

When I select the third tab, I now open the application preferences by overriding the viewDidAppear function in ThirdViewController.swift , for example:

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

However, before opening the settings, I would like to return the active tab to the first tab. How to do it elegantly in Swift.

The following does not work:

 self.tabBarController.selectedIndex = 0 

Since the UIViewController class does not have a tabBarController .

Brian.

+7
ios swift uitabbarcontroller
source share
6 answers

User Omkar answered 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 } 
+8
source share

I followed @Paolo Sangregorio way Code for this as follows

in appdelegate find applicationDidBecomeActive function and add these lines

 let tabBarController = self.window?.rootViewController as! UITabBarController tabBarController.selectedIndex = 0 
+5
source share
 //Use viewWillAppear (instead of) viewDidAppear to prevent a screen flicker var freshLaunch = true override func viewWillAppear(animated: Bool) { if freshLaunch == true { freshLaunch = false self.tabBarController.selectedIndex = 2 } } 
+1
source share

If this is a tab bar application, you must have the tabbarcontroller variable in your appdelegate. You can set the current tab by setting SelectedIndex to this variable from appdelegate.

0
source share

If you use a tab item

Swift 3
@IBOutlet weak var Tabbar: UITabBar!

override func viewDidLoad () {
...
...
...
tabBar.selectedItem = tabBar.items! [newIndex]

}

0
source share

If you want him to come immediately. Yo can be used in viewDidLoad ()

 override open func viewDidLoad() { super.viewDidLoad() // Set Default tab self.selectedIndex = 1 } 
0
source share

All Articles