简体   繁体   中英

Programatically change selected tab for IOS using Swift

I'm a little stuck with this one,

I have a logout button on my app and when I tap it I want to change the selected tab of my tab bar controller to the tab that's selected when the app loads up (index 0) (this should trigger the "sign in to continue" view)

A little more context

My app's root view is a TabBarController and each tab is declared like this:

let friends = CalendarNavigationController(rootViewController: FriendsListViewController())
    friends.title = "Friends"
    friends.tabBarItem.image = UIImage(named: "icon_friends")

This is where I want to send the user after logging out, to trigger a WelcomeViewController

let myMonth = CalendarNavigationController(rootViewController: CalendarViewController())
myMonth.title = "My Month"
myMonth.tabBarItem.image = UIImage(named: "icon_me")

the controllers are assigned with this line: viewControllers = [myMonth, friends, notification, more]

The logout button is inside a UserManagerViewController which is presented modally from the SettingsViewController (poorly named as "more" in the Tab Bar)

(almost there)

the button successfully calls this function when tapped:

@objc func doLogout(){
    print("Logout")
    do {
       // try  Auth.auth().signOut()
        self.dismiss(animated: true) {
            print(self.parent?.tabBarController) <--- This is nil
            self.parent?.tabBarController?.selectedViewController = self.parent?.tabBarController?.viewControllers![0]
            
        }
    } catch {
        
    }
}

I have tried .selectedViewController (as you can see from my code) and also .selectedIndex[0] ... as far as I can tell nothing seems to be happening, presumably because the self.parent?.tabBarController seems to be nil.

Does anybody have any ideas as to where I've gone wrong or how I might make this work?

Thanks:)

You can try

@objc func doLogout(){
    print("Logout")
    do {
        try  Auth.auth().signOut()
        self.dismiss(animated: true) {
            if let tab = (UIApplication.shared.delegate as! AppDelegate).window?.rootViewController as? UITabBarController {
               tab.selectedIndex = 0 
            }
        }
    } catch {
        
    }
}

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