Custom Back button action?

I need to perform a custom action when the Back button is pressed in a UINavigationView. In some cases I need to prevent the top view controller from being popped, so I can't just monitor viewWillDisappear or use a delegate on the navigation controller.


I tried setting the delegate property of the navigation controller's navigation bar, figuring I could then implement the shouldPopItem method, but this doesn't work: attempting to do so throws a runtime exception "Cannot manually set the delegate on a UINavigationBar managed by a controller".


I know I can replace the Back button with a custom UIBarButton, but I don't know how to style a custom button such that it mimics the default button's appearance and title. Is there a good way to do this (good meaning it will continue to work as iOS changes things, not by hard-coding the way it looks right now)?


I also tried accessing the default button via the navigation item's leftBarButton property, but all I got was nil. Is there a way to access the actual Back button that the UINavigationController has created?


Any other way to do this?


Thanks,

Frank

Replies

Just make a leftBarButtonItem with the title set to "< Back".

Sure, it won't look quite the same but the user is entitled to know it isn't 'really' a back button.

If you want you could tell the child controller what the parent's self.title is and use that rather than "Back". I think self.presentingViewController.title might work:

    UIBarButtonItem *dismissButton=[[UIBarButtonItem alloc] 
            initWithTitle:[NSString stringWithFormat:@"< %@",self.presentingViewController.title]
            style:UIBarButtonItemStyleDone 
            target:self
    self.navigationItem.leftBarButtonItem = dismissButton;