實現攔截 UIViewController 的 pop 操作,常見有兩種方式:
UIBarButtonItem,用自己的 item 替換系統返回按鈕,從而完全掌控點擊行為。UINavigationController 的 Category,定製 navigationBar:shouldPopItem: 的判斷邏輯。第二種方式侵入性更小,對已有頁面幾乎零改動,實用性更強。下面是一個完整實現。
#import <UIKit/UIKit.h>
@protocol BackButtonHandlerProtocol <NSObject>
@optional
// 在 UIViewController 的子類中重寫此方法,即可攔截「返回」按鈕的點擊
- (BOOL)navigationShouldPopOnBackButton;
@end
@interface UIViewController (BackButtonHandler) <BackButtonHandlerProtocol>
@end
#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 {
// iOS 7.1 的兼容處理
// 參考:https://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
第一步,在需要攔截的 UIViewController 中引入頭文件:
#import "UIViewController+BackButtonHandler.h"
第二步,實現 navigationShouldPopOnBackButton 方法,返回 NO 即表示攔截:
- (BOOL)navigationShouldPopOnBackButton {
[[[UIAlertView alloc] initWithTitle:@"提示"
message:@"確定返回上一界面?"
delegate:self
cancelButtonTitle:@"取消"
otherButtonTitles:@"確定", nil] show];
// 返回 NO 表示攔截 pop 事件
return NO;
}
這樣一來,用戶點擊導航欄返回按鈕時,會先彈出確認框,只有確認後才真正返回上一頁。