Checking if a UIViewController is about to get Popped from a navigation stack?

后端 未结 15 906
说谎
说谎 2020-12-04 19:17

I need to know when my view controller is about to get popped from a nav stack so I can perform an action.

I can\'t use -viewWillDisappear, because that gets called

相关标签:
15条回答
  • 2020-12-04 19:30

    I tried this:

    - (void) viewWillDisappear:(BOOL)animated {
        // If we are disappearing because we were removed from navigation stack
        if (self.navigationController == nil) {
            // YOUR CODE HERE
        }
    
        [super viewWillDisappear:animated];
    }
    

    The idea is that at popping, the view controller's navigationController is set to nil. So if the view was to disappear, and it longer has a navigationController, I concluded it was popped. (might not work in other scenarios).

    Can't vouch that viewWillDisappear will be called upon popping, as it is not mentioned in the docs. I tried it when the view was top view, and below top view - and it worked in both.

    Good luck, Oded.

    0 讨论(0)
  • 2020-12-04 19:32

    You can observe the notification:

    - (void)viewDidLoad{
        [super viewDidLoad];
        [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(navigationControllerWillShowViewController:) name:@"UINavigationControllerWillShowViewControllerNotification" object:nil];
    }
    
    - (void)navigationControllerDidShowViewController:(NSNotification *)notification{
        UIViewController *lastVisible = notification.userInfo[@"UINavigationControllerLastVisibleViewController"];
        if(lastVisible == self){
            // we are being popped
        }
    }
    
    0 讨论(0)
  • 2020-12-04 19:36

    I don't think there is an explicit message for this, but you could subclass the UINavigationController and override - popViewControllerAnimated (although I haven't tried this before myself).

    Alternatively, if there are no other references to the view controller, could you add to its - dealloc?

    0 讨论(0)
  • 2020-12-04 19:36

    Maybe you could use UINavigationBarDelegate's navigationBar:shouldPopItem protocol method.

    0 讨论(0)
  • 2020-12-04 19:38

    Try overriding willMoveToParentViewController: (instead of viewWillDisappear:) in your custom subclass of UIViewController.

    Called just before the view controller is added or removed from a container view controller.

    - (void)willMoveToParentViewController:(UIViewController *)parent
    {
        [super willMoveToParentViewController:parent];
        if (!parent) {
            // `self` is about to get popped.
        }
    }
    
    0 讨论(0)
  • 2020-12-04 19:38
    - (void)viewDidDisappear:(BOOL)animated {
        [super viewDidDisappear:animated];
    
        const BOOL removingFromParent = ![self.navigationController.viewControllers containsObject:self.parentViewController];
        if ( removingFromParent ) {
            // cleanup
        }
    }
    
    0 讨论(0)
提交回复
热议问题