开发者

iOS: How to Recognize that We Got Back from a Child UIViewController within the Parent UIViewController?

Let's say that I have 2 UIViewControllers on a stack within a UINavigationController. In the "parent" we call "[self.navigationController pushViewController:childViewController animated:YES];" upon some user action and in the "child" we call "[self.navigationController popViewControllerAnimated:YES];" upon some user action.

How can we recognize within the parent that we just got back?

Is there some "event" driven method that can recognize that this开发者_运维知识库 popViewControllerAnimated action was called from the child?


It seems like you're using this child controller as a modal in that it can be 'dismissed'. If that is the case, try to follow Apple's patterns that they use for UIAlertViews.

If that is the case, I'd do either of the following to implement a delegate pattern(delegate vs block is a huge debate that I will not get into here) so the owner(the one that pushes the child on) knows when its dismissed:

  • Create a protocol (ChildControllerDelegate), have one method in it childControllerWasDismissed:(ChildController *)
  • add a block property(make sure its a copy property, not retain) to the ChildController

You'll then want to call the delegate method or block on viewDidDisappear. If you want finer grain control, have a delegate method or block that corresponds viewWillDisappear / viewDidDisappear.


I'd successfully resolved this by setting navigationController?.delegate = self and then implementing this method to determine whether the current view controller is shown again after a pop.

func navigationController(navigationController: UINavigationController, didShowViewController viewController: UIViewController, animated: Bool) {
        if viewController == self {
            // we got back
        } else {
            // some other controller was pushed
        }
    }


There's a few way to hint at that. What you can do, is call the popViewControllerAnimated from the parent. You can do that by passing a block to the child controller that would then execute the said block and thus popping would be done by the parent controller.

You can also use the UINavigationController delegate to be notified when a UIViewController will be dismissed:

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated;

This method will let you know which VC will be shown and you can check if the current (not yet popped) VC is the child you were looking for.

You can also do some trick with - (void)viewWillAppear: but this might require some hacks.


First read this, it will help you understand what is going on with view controllers.

Then implement viewWillAppear: and viewDidAppear: in your parent view controller to log a message.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜