UIViewController+BackButtonHandler.h
#import <UIKit/UIKit.h>
@protocol BackButtonHandlerProtocol <NSObject>
@optional
// 重写下面的方法以拦截导航栏返回按钮点击事件,返回 YES 则 pop,NO 则不 pop
-(BOOL)navigationShouldPopOnBackButton;
@end
// 表示遵循这个代理
@interface UIViewController (BackButtonHandler) <BackButtonHandlerProtocol>
@end
UIViewController+BackButtonHandler.h是UIViewController的分类,在.h里声明一个代理方法
UIViewController+BackButtonHandler.m
#import "UIViewController+BackButtonHandler.h"
@implementation UIViewController (BackButtonHandler)
@end
@implementation UINavigationController (ShouldPopOnBackButton)//UINavigationController的分类
- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item {
//判断是否返回
if([self.viewControllers count] < [navigationBar.items count]) {
return YES;
}
BOOL shouldPop = YES;
//获取最上层的UIViewController
UIViewController* vc = [self topViewController];
//判断是否有navigationShouldPopOnBackButton方法
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;
}
@end
- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item
这个方法是导航栏将要返回时的方法,方法中返回YES时,导航栏将返回到上个界面,NO就不返回。这个方法需要注意的是,此方法不能在UIViewController中直接调用,必须写在创建的UINavigationController的地方。所以在UIViewController+BackButtonHandler.m创建了UINavigationController的分类@implementation UINavigationController (ShouldPopOnBackButton)
respondsToSelector方法是用来判断是否有以某个名字命名的方法