Wednesday, 22 April 2015

UIViewController default back button action

UIViewController+BackButtonHandler.h

#import <UIKit/UIKit.h>

@protocol BackButtonHandlerProtocol <NSObject>
@optional

-(BOOL)navigationShouldPopOnBackButton;
@end

@interface UIViewController (BackButtonHandler) <BackButtonHandlerProtocol>

@end

UIViewController+BackButtonHandler.m

#import "UIViewController+BackButtonHandler.h"

@implementation UIViewController (BackButtonHandler)

@end

@implementation UINavigationController (ShouldPopOnBackButton)

- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item {

if([self.viewControllers count] < [navigationBar.items count]) {
return YES;
}

BOOL shouldPop = YES;
UIViewController* vc = [self topViewController];
if([vc respondsToSelector:@selector(navigationShouldPopOnBackButton)]) {
shouldPop = [vc navigationShouldPopOnBackButton];
}

if(shouldPop) {
dispatch_async(dispatch_get_main_queue(), ^{
[self popViewControllerAnimated:YES];
});
} else {
for(UIView *subview in [navigationBar subviews]) {
if(subview.alpha < 1.) {
[UIView animateWithDuration:.25 animations:^{
subview.alpha = 1.;
}];
}
}
}

return NO;
}

@end

put this code in your child view controller 

#import "UIViewController+BackButtonHandler.h"

-(BOOL) navigationShouldPopOnBackButton
{
[[[UIAlertView alloc] initWithTitle:@"Confirmation" message:@"Are you sure you want to go back?"
  delegate:self cancelButtonTitle:@"No" otherButtonTitles:@"Yes", nil] show];
return NO;
}

- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex
{
if(buttonIndex==1) {
[self.navigationController popViewControllerAnimated:YES];
}
}


No comments:

Post a Comment