攔截系統自帶的Pop事件
首先,在開發中我遇到一個問題,用故事版將控制器連接起來,之後就有了系統自帶的返回按鈕(大家都知道,說的很直白)。
當我想點擊返回按鈕的時候,根據自己的情況再確定反不反回上一個控制器。解決方案:
我看到了[南峯子的技術博客](http://southpeak.github.io/blog/archives/)
抄過來的,不是原創,只是我在找相關解決方案的時候不好找,就多寫寫了。
.h
#import <UIKit/UIKit.h>
@protocol BackButtonHandlerProtocol <NSObject>
@optional
-(BOOL)navigationShouldPopOnBackButton;
@end
@interface UIViewController (BackButtonHandler)<BackButtonHandlerProtocol>
@end
.m
#import "UIViewController+BackButtonHandler.h"
@implementation UIViewController (BackButtonHandler)
@end
- (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 {
for(UIView *subview in [navigationBar subviews]) {
if(subview.alpha < 1.) {
[UIView animateWithDuration:.25 animations:^{
subview.alpha = 1.;
}];
}
}
}
return NO;
}
@end:
-(BOOL)navigationShouldPopOnBackButton
{
NSLog(@"捕捉到返回事件");
UIAlertView *alerView = [[UIAlertView alloc] initWithTitle:@"提示:" message:@"您確定要放棄編輯嗎?" delegate:self cancelButtonTitle:@"確定" otherButtonTitles:@"不", nil];
alerView.tag = 1000;
[alerView show];
return NO;
}
#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (alertView.tag == 1000) {
if(buttonIndex == 0){
[self.navigationController popViewControllerAnimated:YES];
}else{
}
}
}