截取iOS系統(tǒng)自帶返回按鈕事件
當用戶點的不是保存而是系統(tǒng)自帶的返回,我就彈出一個提示框問是否保存后再返回。相信大家開發(fā)過程中也經(jīng)常會遇到這樣的需求,我這里講一下如何簡單的解決這個問題吧~
下面分兩種情況處理這件事
第一種:返回鍵采用的是系統(tǒng)的返回鍵
通過建立類別來實現(xiàn)
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里面的具體使用方法:
//實現(xiàn)方法
-(BOOL)navigationShouldPopOnBackButton{
return YES;
}
代碼下載地址:https://github.com/xiaoshunliang/OverrideBackButtonDemo
第二種:對于自定義的返回按鈕
BaseViewController.h中
@protocol BackButtonHandlerProtocol <NSObject>
@optional
//點擊返回按鈕時做特殊處理的時候 實現(xiàn)這個協(xié)議方法
-(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;
//實現(xiàn)返回按鈕做特殊處理
if([self respondsToSelector:@selector(navigationShouldPopOnBackButton)]) {
shouldPop = [self.backButtonDelegate navigationShouldPopOnBackButton];
}
if(shouldPop) {
dispatch_async(dispatch_get_main_queue(), ^{
[self.navigationController popViewControllerAnimated:YES];
});
}
}
實際使用:
繼承于BaseViewController
實現(xiàn)協(xié)議方法 BackButtonHandlerProtocol
self.backButtonDelegate = self;
實現(xiàn)協(xié)議方法
-(BOOL)navigationShouldPopOnBackButton{
return YES;
}
代碼下載地址:https://github.com/xiaoshunliang/CustomBackButtonDemo