May 29, 2009

Trapping the UINavigationBar Back Button (part 3)

I have covered the topic of trapping the back button in order to do something. These previous forays are part 1 and part 2. I had implemented my solution from part 2, and it is working well. However, I am always on the look out for a better, cleaner solution. Just recently, an anonymous commenter pointed out something I had not noticed before: the UINavigationBarDelegate prototype has a method called navigationBar:shouldPopItem: It is called just before the item is popped. If it returns NO, then the pop won't actually happen. But this can be the perfect way to insert some logic before the pop happens (and return YES at the end). Here is how you would implement your back-button press event logic:
- (BOOL)
navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item
   //insert your back button handling logic here

   // let the pop happen
   return YES;
This is so much cleaner than my previous solution. I love it! Thanks to whomever pointed out the obvious.


  1. Where would you put and how would you call this code?

  2. So i can use this function to pass data back to my master view controller right?