检测视图控制器何时从弹出窗口出现

Moc*_*cha 3 cocoa-touch uiviewcontroller uinavigationcontroller ios

我正在导航堆栈的深处弹出一个视图控制器.是否可以检测视图控制器是从推送还是弹出显示?

nav stack:

[A] -> [B] -> [C] -> [D] -> [E]
Run Code Online (Sandbox Code Playgroud)

[E]弹出[B]

nav stack:

[A]  -> [B] // Possible to detect if B appears from a pop?
Run Code Online (Sandbox Code Playgroud)

rma*_*ddy 8

在视图控制器B中,实现viewWillAppearviewDidAppear.在那里,使用isMovingToParentisBeingPresented查看它出现在什么条件下:

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

    if !isBeingPresented && !isMovingToParent {
        // this view controller is becoming visible because something that was covering it has been dismissed or popped
    }
}
Run Code Online (Sandbox Code Playgroud)

以下是人们可能会发现的这些属性的更一般用法:

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

    if isMovingToParent {
        // this view controller is becoming visible because it was just push onto a navigation controller or some other container view controller
    } else if isBeingPresented {
        // this view controller is becoming visible because it is being presented from another view controller
    } else if view.window == nil {
        // this view controller is becoming visible for the first time as the window's root view controller
    } else {
        // this view controller is becoming visible because something that was covering it has been dismissed or popped
    }
}
Run Code Online (Sandbox Code Playgroud)

上述逻辑不包括一种情况 - 当视图控制器首次显示为窗口时viewWillAppear.如果你需要检查那个案子,我想viewDidAppear会是,isMovingToParent但我现在无法测试.

  • 根选项卡栏控制器也不是这种情况。即使您切换选项卡,该条件也将成立。 (3认同)
  • 一个疑问:在这种情况下,不是"isBeingPresented"总是"假"吗?我的意思是,在这种情况下可以省略它,对吧?......或者如果我错了,它可能是这个变量`true`? (2认同)