iosswiftswift3uitabbarcontrollerunwind-segue

Swift 3: UITabBarController change tab on unwind


I have UITabBarController. From the Home tab, I segued to a ThankYouVC.

When I unwind from ThankYouVC, I want to change the selected tab.

What I've tried:

HomeVC

@IBAction func unwindToMain(segue:UIStoryboardSegue) {
    print("unwind")
    self.tabBarController?.selectedIndex = 0
}

The console log prints unwind, but doesn't change the index.

Another attempt:

enum Notifications: String, NotificationName {
    case QRDoneNotification
}

override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(unwindCallBack), name: Notification.Name("QRDoneNotification"), object: nil)
}

@IBAction func unwindToMain(segue:UIStoryboardSegue) {
    print("unwind")
    NotificationCenter.default.post(name: Notifications.QRDoneNotification.name, object: nil)
}

func unwindCallBack() {
    self.tabBarController?.selectedIndex = 0
}

Still no luck!!

Help me out.


Solution

  • The problem is that an unwind segue unwinds to the view controller that holds the function. So that's where you end up.

    One solution: subclass UITabBarController and put your unwind segue there.

    class MyTabBarController: UITabBarController {
    
        @IBAction func unwindToMain(segue:UIStoryboardSegue) {
            print("Unwinding to the custom tab bar controller...")
            selectedIndex = 1
        }
    
    }
    

    So, add that class to your project... set the Custom Class of your current UITabBarController to MyTabBarController... Assign your Exit / Unwind segue to this new one, and don't forget to delete your existing unwindToMain() function and unwind connection.