Custom action on Back Button UINavigationController
Yes! There is a way of using the backBarButton with a custom action. No, it’s not by overriding the backBarButton property of navigationItem. This is not an ugly solution with images that simulate the “Back”-button (arrow-shaped.) It’s possible to use the backBarButton for popping the current viewController as normal, but than with other animations such as UIViewAnimationTransitionCurlDown.
Enough said, the solution is simple. You have to subclass your navigationController’s popViewControllerAnimated:(BOOL)animated. So create a custom navigationController:
customNavigationController.h
#import @interface customNavigationController : UINavigationController {} @end
And a custom “popViewControllerAnimated:(BOOL)animated”, this popViewControllerAnimated-function uses the “UIViewAnimationTransitionCurlDown” when popping from a SettingsTableView.
customNavigationController.m
#import "customNavigationController.h" #import "SettingsTableController.h" @implementation customNavigationController - (UIViewController *)popViewControllerAnimated:(BOOL)animated { if([[self.viewControllers lastObject] class] == [SettingsTableController class]){ [UIView beginAnimations:nil context:NULL]; [UIView setAnimationDuration: 1.00]; [UIView setAnimationTransition:UIViewAnimationTransitionCurlDown forView:self.view cache:NO]; UIViewController *viewController = [super popViewControllerAnimated:NO]; [UIView commitAnimations]; return viewController; } else { return [super popViewControllerAnimated:animated]; } } @end
Use your custom navigationController in your appDelegate:
customNavigationController *navigationController = [[customNavigationController alloc] initWithRootViewController:rootView];
This code worked a treat. It’s so simple and obvious.
looks great, but I’m using xib. mmm…
Isn’t it possible to define your UINavigationController object in Interface Builder as a customNavigationController instance?
Ah got it working with the IB as mentioned above.
However, I’d like to ask the user if there sure they want to quit.
Don’t know how to do that. I tried commenting out the code within the IF block, but it keeps my current controller and shows the main controller title.
What should I do here ?
You could create a delegate method like “-(BOOL)navigationController:shouldPopViewController:”. Make your window the delegate. Return NO to that method. Display an UIAlertView and then pop again and return YES to that delegate method.
Could you provide an example of that ?
Yes, I will rewrite the article when I have time, providing the example.