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

后端 未结 15 949
说谎
说谎 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条回答
  •  Happy的楠姐
    2020-12-04 19:26

    Fortunately, by the time the viewWillDisappear method is called, the viewController has already been removed from the stack, so we know the viewController is popping because it's no longer in the self.navigationController.viewControllers

    Swift 4

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
    
        if let nav = self.navigationController {
            let isPopping = !nav.viewControllers.contains(self)
            if isPopping {
                // popping off nav
            } else {
                // on nav, not popping off (pushing past, being presented over, etc.)
            }
        } else {
            // not on nav at all
        }
    }
    

    Original Code

    - (void)viewWillDisappear:(BOOL)animated {
        [super viewWillDisappear:animated];
        if ((self.navigationController) && 
            (![self.navigationController.viewControllers containsObject:self])) {
            NSLog(@"I've been popped!");
        }
    }
    

提交回复
热议问题