Checking if a UIViewController is about to get Pop

2019-01-16 17:55发布

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 when the view controller is moved off screen for ANY reason (like a new view controller being pushed on top).

I specifically need to know when the controller is about to be popped itself.

Any ideas would be awesome, thanks in advance.

12条回答
爷的心禁止访问
2楼-- · 2019-01-16 18:23

Try making this check in viewwilldisappear if ([self.navigationController.viewControllers indexOfObject:self] == NSNotFound) { //popping of this view has happend. }

查看更多
该账号已被封号
3楼-- · 2019-01-16 18:29

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.
    }
}
查看更多
相关推荐>>
4楼-- · 2019-01-16 18:29

You can use this one:

if(self.isMovingToParentViewController)
{
    NSLog(@"Pushed");
}
else
{
    NSLog(@"Popped");
}
查看更多
Deceive 欺骗
5楼-- · 2019-01-16 18:33

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

查看更多
beautiful°
6楼-- · 2019-01-16 18:34

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?

查看更多
叛逆
7楼-- · 2019-01-16 18:38

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.

查看更多
登录 后发表回答