When using a UINavigationController, when the user is "diving in deeper" (pushing yet another controller on the stack), I have an opportunity to handle that in

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender

But how do I handle the opposite? When the user presses the back button, and a controller becomes the top controller again, I'd like it to potentially update some state because the controllers on the stack may have changed some things I want to reflect in the now visible controller.

Or, by analog, when I use modal segues to present new controllers, I get to pick a method that is called as an unwind segue when the presented controller exits. How can I do the same with navigation stack managed controllers?

(feel free to put a better title on this)

有帮助吗?

解决方案

It turns out that you can disambiguate based on the response to isMovingToParentViewController. If it is YES your controller has just been placed topmost on the stack. If it is NO, your controller is returning to topmost, another push on top of it being popped. Example:

-(void)viewWillAppear:(BOOL)animated{
    if (self.isMovingToParentViewController == NO) { // returning from even higher controller
        [self updateForChangesThatMayHaveHappenedInSubController];
    }
    [super viewWillAppear:animated];
}

其他提示

You can use the viewWillAppear: method to update the ui before the view becomes visible. If you want to pass data back up the chain, you should assign yourself as the delegate to your child and call an update function on the delegate before popping.

To have many clients (viewControllers in this case) update their views in response to a change of some shared data, you should use NSNotifications, or you should have the viewControllers observe certain values on the shared data-object (KVO). ViewController should be as autistic as possible, meaning that they know all about the interface of downstream viewControllers, but have absolutely no idea about what viewController is upstream (talking back to an upstream viewController is usually done through delegation, and only to signal events that might indicate some change in viewController hierarchy, not in shared data state).

Checkout out the stanford lectures by Paul Hegarty, he explains this much better then I can.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top