實現攔截UIViewController
的pop
操做有兩種方式:git
UIBarButtonItem
來實現自定義的返回操做。UINavigatonController
的Category
,來定製navigationBar: shouldPopItem:
的邏輯。UIViewController+BackButtonHandler.h:github
#import <UIKit/UIKit.h> @protocol BackButtonHandlerProtocol <NSObject> @optional // Override this method in UIViewController derived class to handle 'Back' button click -(BOOL)navigationShouldPopOnBackButton; @end @interface UIViewController (BackButtonHandler) <BackButtonHandlerProtocol> @end
UIViewController+BackButtonHandler.m:async
#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 { // Workaround for iOS7.1. Thanks to @boliva - http://stackoverflow.com/posts/comments/34452906 for(UIView *subview in [navigationBar subviews]) { if(0. < subview.alpha && subview.alpha < 1.) { [UIView animateWithDuration:.25 animations:^{ subview.alpha = 1.; }]; } } } return NO; }
使用:ide
UIViewController
當中引入頭文件#import "UIViewController+BackButtonHandler.h"
UIViewController
中實現navigationShouldPopOnBackButton
方法。- (BOOL)navigationShouldPopOnBackButton{ [[[UIAlertView alloc] initWithTitle:@"提示" message:@"肯定返回上一界面?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"肯定", nil] show]; //renturn no 攔截pop事件 return NO; }
參考:post