Determine if view that appears was pushed or came

2020-07-03 08:07发布

问题:

Is there a way to tell if a new controller came from a navigation back button or was pushed onto the stack? Id like to reload data only for pushing on the navigation stack, not on a back button press.

回答1:

As of iOS 5.0 you can do this:

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    if (self.isBeingPresented || self.isMovingToParentViewController) {
        // "self" is being shown for the 1st time, not because of a "back" button.
    }
}


回答2:

If your push also includes instantiating the view controller, put your push-only logic in viewDidLoad. It will not be called on back because it has already been loaded.



回答3:

You could implement the UINavigationControllerDelegate and override the `navigationController:didShowViewController:animated:' method. You'll then have to check the returned view controller to make a determination as to whether you came back from the expected view controller.

- (void)navigationController:(UINavigationController*)navigationController didShowViewController:(UIViewController*)viewController animated:(BOOL)animated
{
    if (yourPushedViewController == viewController)
    {
        // Do something
    }
}