简体   繁体   中英

How to revert back to a previous view from current view in a UITabBarController?

I am a beginner to XCode and Swift. Currently, I have an app with a UITabBarController that is connected to three UIViewControllers: Home, Add, and Search. How would I implement a "cancel" button in the Add view controller so that it will return to the previous view once tapped?

你需要改变

self.tabBarController?.selectedIndex = // 0 home , 1 add , 2 search

You can memorize the previously selected tab index before a user switches to another tab by implementing shouldSelect defined in UITabBarControllerDelegate .

class MyTabBarController: UITabBarController, UITabBarControllerDelegate
{
    var previousSelectedIndex: Int?

    override func viewDidLoad() {
        ...
        tabBarController.delegate = self
    }

    func tabBarController(tabBarController: UITabBarController, shouldSelect: UIViewController) -> Bool {
        previousSelectedIndex = tabBarController.selectedIndex
        return true
    }

    func cancel() {
        if let index = previousSelectedIndex {
            self.selectedIndex = index
        }
    }
}

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