iOS how to detect programmatically when top view controller is popped?

后端 未结 10 1344
逝去的感伤
逝去的感伤 2020-12-04 17:32

Suppose I have a nav controller stack with 2 view controllers: VC2 is on top and VC1 is underneath. Is there code I can include in VC1 that will detect that VC2 has just be

10条回答
  •  执念已碎
    2020-12-04 18:09

    isMovingTo/FromParentViewController won't work for pushing and popping into a navigation controller stack.

    Here's a reliable way to do it (without using the delegate), but it's probably iOS 7+ only.

    UIViewController *fromViewController = [[[self navigationController] transitionCoordinator] viewControllerForKey:UITransitionContextFromViewControllerKey];
    
    if ([[self.navigationController viewControllers] containsObject:fromViewController])
    {
        //we're being pushed onto the nav controller stack.  Make sure to fetch data.
    } else {
        //Something is being popped and we are being revealed
    }
    

    In my case, using the delegate would mean having the view controllers' behavior be more tightly coupled with the delegate that owns the nav stack, and I wanted a more standalone solution. This works.

提交回复
热议问题