Monthly Archives: June 2012
Posted by pricerhythm
Well, I was struggling with this for a couple of days, and decided to share it.
We are developing an iphone version for our application and during the development I came up with the following problem.
We have a UINavigationController in our app that is responsible for managing the navigations.
In the navigationController we have a customized back button:
navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@”back” style:UIBarButtonItemStylePlain target:nil action:nil];
The problem with this button is that although it lets you define target and action for your logic in case of click, it is not calling them. This behavior is also explained in the apple documentation, but no solution is given to the problem.
So at this point if you want to add your logic when back button is pressed you may find yourself doing the following and reinventing the wheel:
- Implementing the back button by yourself
- Struggling with UINavigationControllerDelegate
- Subclassing the UINavigationController, when you really are not advised to do this according to https://developer.apple.com/library/ios/#documentation/UIKit/Reference/UINavigationController_Class/Reference/Reference.html
However, there is a really simple solution that can be used:
If we are trying to simplify the problem, this is the scenario:
- Back button is pressed
- viewWillDisappear is called
So, we can insert our code in viewWillDisappear method. But (since we always have a but) this method can also be called when there is a new view that is pushed in the stack above our view, which makes it disappear.
How can we check this? Actually it is really simple 🙂
In the View Controller programming guide [https://developer.apple.com/library/ios/#featuredarticles/ViewControllerPGforiPhoneOS/RespondingtoDisplay-Notifications/RespondingtoDisplay-Notifications.html#//apple_ref/doc/uid/TP40007457-CH12-SW1] you can find out in which state the viewWillDisappear method is called, if it is by calling the back button so it returns to the parent controller or the new controller is pushed above.
The code should look like this:
// Checking if we are disappearing because of the back button
if ([self isMovingFromParentViewController])
// In case that back button is pressed, insert your code here
Chief App Developer