Search code examples
ioscocoa-touchuiviewcontrolleruinavigationcontroller

Detect when view controller appears from pop


I am popping a view controller deep within a navigation stack. Is it possible to detect if the view controller is being shown from a push or a pop?

nav stack:

[A] -> [B] -> [C] -> [D] -> [E]

[E] pops to [B]

nav stack:

[A]  -> [B] // Possible to detect if B appears from a pop?

Solution

  • In view controller B, implement either viewWillAppear or viewDidAppear. In there, use isMovingToParent and isBeingPresented to see under what conditions it is appearing:

    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
        }
    }
    

    Below is a more general use of these properties that people may find handy:

    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
        }
    }