UIViewController+BackButtonHandler是用來攔截系統(tǒng)導(dǎo)航欄返回事件舶衬,并提供方法來處理返回事件
UIViewController+BackButtonHandler.h
#import <UIKit/UIKit.h>
@protocol BackButtonHandlerProtocol <NSObject>
@optional
// 重寫下面的方法以攔截導(dǎo)航欄返回按鈕點擊事件系洛,返回 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 后惜索,復(fù)原返回按鈕的狀態(tài)
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
這個方法是導(dǎo)航欄將要返回時的方法征绸,方法中返回YES時克锣,導(dǎo)航欄將返回到上個界面赖晶,NO就不返回律适。這個方法需要注意的是,此方法不能在UIViewController中直接調(diào)用遏插,必須寫在創(chuàng)建的UINavigationController的地方捂贿。所以在UIViewController+BackButtonHandler.m創(chuàng)建了UINavigationController的分類@implementation UINavigationController (ShouldPopOnBackButton)
respondsToSelector方法是用來判斷是否有以某個名字命名的方法