views:

110

answers:

1

In a navigation controller app, assuming you've assigned a title to the root controller, the pushed view will have a back button with that title in the top left of its navigation bar. That is automatic. How can I execute code based on the click event of that back button?

+1  A: 

Implement UINavigationControllerDelegate

@protocol UINavigationControllerDelegate <NSObject>

@optional

// Called when the navigation controller shows a new top view controller via a push, pop or setting of the view controller stack.
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated;
- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated;

@end

Edit: example for a simple two level hierarchy, but can easily be updated to more)

Make your root view controller the UINavigationController delegate (e.g. in viewDidLoad) and then implement as follows:

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    if (viewController == self )
    {
        if (lastView == theOtherView)
        {
            // Pop from other view to root view
        }
    }
    else if (viewController == theOtherView)
    {
        // push to other view
    }
    lastView = viewController;
}
cidered
Right but if the root controller has two paths out of it - one is push view1 from the root controller tableview and the other is push view2 via an info icon, how do I tell which view I came from when going back to the root controller?
4thSpace
cidered