简体   繁体   中英

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, eg 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 , eg:

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.

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     
}

I followed @Paolo Sangregorio way The code to do it as follows

in appdelegate find applicationDidBecomeActive function and add this lines

let tabBarController = self.window?.rootViewController as! UITabBarController
tabBarController.selectedIndex = 0
//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
    }
}

If it is a tab bar application you should have the tabbarcontroller variable in your appdelegate. You can set the current tab by setting the selectedIndex on that variable, from the appdelegate.

In case you are using Tab bar item

Swift 3
@IBOutlet weak var Tabbar: UITabBar!

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

}

If you want him to come without delay. Yo can use in viewDidLoad()

override open func viewDidLoad() {
    super.viewDidLoad()

    // Set Default tab
    self.selectedIndex = 1
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM