Determine viewWillAppear from Popped UINavigationController or UITabBarController

為{幸葍}努か 提交于 2019-12-05 12:36:38

Sounds like a good use of the UITabBarControllerDelegate.

First, add a Bool property on your ViewController comingFromTab:

class MyViewController: UIViewController {
    var comingFromTab = false

    // ...
}

Set your UITabBarControllerDelegate to whatever class you want and implement the method shouldSelectViewController. You may also want to subclass UITabBarController and put them in there.

func tabBarController(tabBarController: UITabBarController, shouldSelectViewController viewController: UIViewController) -> Bool {

    if let myViewController = viewController as? MyViewController {
        myViewController.comingFromTab = true
}

If your tab's initial view controller is a UINavigationController, you will have to unwrap that and access it's first view controller:

if let navController = viewController as? UINavigationController {
    if let myViewController = navController.viewControllers[0] as? MyViewController {
        // do stuff
    }
}

Lastly, add whatever functionality you need in viewWillAppear in your view controller:

override func viewDidAppear(animated: Bool) {
    super.viewWillAppear(animated)

    // ...
    if comingFromTab {
        // Do whatever you need to do here if coming from the tab selection
        comingFromTab = false
    }
}

There is no way to know for sure. So I guess the easiest way is to add some variable that you will have to change before popping back to that view controller and checking it's state in viewWillAppear.

class YourViewController: UIViewController {
    var poppingBack = false

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)

        if !poppingBack {
            // your logic
        }
        else {
            poppingBack = false // reset it for next time
        }
    }
}

// somewhere else in code, suppose yourVC is YourViewController
yourVC.poppingBack = true
self.navigationController.popToViewController(yourVC, animated: true)

You can also try implementing UINavigationControllerDelegate's - navigationController:willShowViewController:animated: method and check if it will be called when presenting your view controller from tab bar.

You can check parentViewController property

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    if parentViewController is UITabBarController {
        // Presented by UITabBarController
    } else if parentViewController is UINavigationController {
        // Presented by UINavigationController
    } else {
        // Presented by ...
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!