一、创建一个UIViewController的分类即可:
1、h文件
#import <UIKit/UIKit.h>
@protocol BackButtonHandlerProtocol <NSObject>
@optional
// 重写下面的方法以拦截导航栏返回按钮点击事件,返回 YES 则 pop,NO 则不 pop
-(BOOL)navigationShouldPopOnBackButton;
@end
@interface UIViewController (BackButtonHandler) <BackButtonHandlerProtocol>
// 当前显示控制器
//-(UIViewController*)currentViewController;
@end
2、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 {
// 取消 pop 后,复原返回按钮的状态
for(UIView *subview in [navigationBar subviews]) {
if(0. < subview.alpha && subview.alpha < 1.) {
[UIView animateWithDuration:.25 animations:^{
subview.alpha = 1.;
}];
}
}
}
return NO;
}
//获取Window当前显示的ViewController
- (UIViewController*)currentViewController{
//获得当前活动窗口的根视图
UIViewController* vc = [UIApplication sharedApplication].keyWindow.rootViewController;
while (1)
{
//根据不同的页面切换方式,逐步取得最上层的viewController
if ([vc isKindOfClass:[UITabBarController class]]) {
vc = ((UITabBarController*)vc).selectedViewController;
}
if ([vc isKindOfClass:[UINavigationController class]]) {
vc = ((UINavigationController*)vc).visibleViewController;
}
if (vc.presentedViewController) {
vc = vc.presentedViewController;
}else{
break;
}
}
return vc;
}
@end
3、⚠️注意⚠️
到有有自定义导航栏返回按钮self.navigationItem.leftBarButtonItem = UIBarButtonItem时,一定要在leftItem的点击事件方法leftItemClick中添加
func leftItemClick(){
var shouldPop = true;
let tempVC = self.topViewController;
let temp = tempVC?.responds(to: #selector(navigationShouldPopOnBackButton));
if temp != nil && temp! == true {
shouldPop = (tempVC?.navigationShouldPopOnBackButton())!;
}
if shouldPop == true {
self.popViewController(animated: true);
}
}