通过在UINavigationController中“弹出”先前的VIewController来检测何时显示ViewController

时间:2019-04-29 13:47:09

标签: ios objective-c uiviewcontroller uinavigationcontroller uikit

请考虑以下导航层次结构:

  

NavigationContrller -> ViewController1 -> ViewController2

我想通过 ViewController2 (即,按NavigationController上的“返回”按钮)来检测何时显示 ViewController1

我感兴趣的方法是- (void)viewWillAppear:(BOOL)animated。如何检查是否通过前进(即 NavigationController -> ViewController1 )或向后(即)呈现了 ViewController1 > ViewController2 -> ViewController1 )?

2 个答案:

答案 0 :(得分:0)

您可以在 viewWillAppear 中检查导航堆栈的控制器顺序,如下所示:

      for controller in self.navigationController!.viewControllers as Array {
                //  print("controller \(controller) at i \(i)") 
      }

答案 1 :(得分:0)

您可以使用Bool来跟踪“推送状态”:

class ViewController1: UIViewController {

    private var isBeingPushed = true

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

        if isBeingPushed {
            print("forwards")
        } else {
            print("backwards")
        }
    }

    override func viewDidDisappear(_ animated: Bool) {
        isBeingPushed = false
        super.viewDidDisappear(animated)
    }

    override func didMove(toParent parent: UIViewController?) {
        if parent == nil {
            isBeingPushed = true
        }
        super.didMove(toParent: parent)
    }

}