截取iOS系统自带返回按钮事件
当用户点的不是保存而是系统自带的返回,我就弹出一个提示框问是否保存后再返回。相信大家开发过程中也经常会遇到这样的需求,我这里讲一下如何简单的解决这个问题吧~
下面分两种情况处理这件事
第一种:返回键采用的是系统的返回键
通过建立类别来实现
UIViewController.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.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 {
// 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;
}
@end
controller里面的具体使用方法:
//实现方法
-(BOOL)navigationShouldPopOnBackButton{
return YES;
}
代码下载地址:https://github.com/xiaoshunliang/OverrideBackButtonDemo
第二种:对于自定义的返回按钮
BaseViewController.h中
@protocol BackButtonHandlerProtocol <NSObject>
@optional
//点击返回按钮时做特殊处理的时候 实现这个协议方法
-(BOOL)navigationShouldPopOnBackButton;
@end
@interface BaseViewController : UIViewController<UITableViewDataSource,UITableViewDelegate,UIGestureRecognizerDelegate>
@property (assign, nonatomic) id<BackButtonHandlerProtocol> backButtonDelegate;
@end
BaseViewController.m中
UIBarButtonItem *leftbtn = [[UIBarButtonItem alloc] initWithImage:[UIImage locatilyImage:@"arrow--return"]
style:UIBarButtonItemStylePlain
target:self action:@selector(dismiss)];
self.navigationItem.leftBarButtonItem = leftbtn;
- (void)dismiss{
BOOL shouldPop = YES;
//实现返回按钮做特殊处理
if([self respondsToSelector:@selector(navigationShouldPopOnBackButton)]) {
shouldPop = [self.backButtonDelegate navigationShouldPopOnBackButton];
}
if(shouldPop) {
dispatch_async(dispatch_get_main_queue(), ^{
[self.navigationController popViewControllerAnimated:YES];
});
}
}
实际使用:
继承于BaseViewController
实现协议方法 BackButtonHandlerProtocol
self.backButtonDelegate = self;
实现协议方法
-(BOOL)navigationShouldPopOnBackButton{
return YES;
}
代码下载地址:https://github.com/xiaoshunliang/CustomBackButtonDemo