系統導航欄左上角的返回按鈕預設會直接 pop 回上一頁。若希望在返回之前插入確認、存檔或其他自訂邏輯,可以透過 UINavigationControllerDelegate 的 navigationBar:shouldPopItem: 來攔截。
UIViewController+BackButtonHandler.h
#import <UIKit/UIKit.h> @protocol BackButtonHandlerProtocol <NSObject> @optional // 在繼承 UIViewController 的子類別中覆寫此方法,即可自訂返回鍵行為 - (BOOL)navigationShouldPopOnBackButton; @end @interface UIViewController (BackButtonHandler) <BackButtonHandlerProtocol> @end
UIViewController+BackButtonHandler.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 {
// iOS 7.1 的變色 workaround
for (UIView *subview in [navigationBar subviews]) {
if (subview.alpha < 1.) {
[UIView animateWithDuration:.25 animations:^{
subview.alpha = 1.;
}];
}
}
}
return NO;
}
@end
這裡有個容易忽略的細節:無論 shouldPop 是 YES 還是 NO,方法最後都必須回傳 NO。原因是回傳 YES 會讓系統自己執行 pop,那就跟程式碼裡手動呼叫 popViewControllerAnimated: 重複了,會一次跳兩頁。所以這個方法的定位是「一律由我自己決定何時 pop」,回傳值永遠是 NO。
而 shouldPop == NO 那個分支之所以要處理 navigationBar 的 alpha,是因為 iOS 7.1 有個已知問題:攔截返回後,返回按鈕的文字會變得透明,需要手動把它調回來。
#import "ViewController.h"
#import "UIViewController+BackButtonHandler.h"
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.title = [NSString stringWithFormat:@"Screen-%d",
(int)self.navigationController.viewControllers.count];
self.navigationItem.rightBarButtonItem =
[[UIBarButtonItem alloc] initWithTitle:@"Next"
style:UIBarButtonItemStylePlain
target:self
action:@selector(onNextBtn:)];
}
- (void)onNextBtn:(id)sender {
[self.navigationController pushViewController:[ViewController new] animated:YES];
}
// 在這個方法中撰寫返回按鈕的事件處理
- (BOOL)navigationShouldPopOnBackButton {
// 這裡可以先彈確認框,使用者確認後再往下走
[self.navigationController popViewControllerAnimated:YES];
return YES;
}
@end
把返回邏輯寫在每個畫面自己的類別裡,比在 push 之前統一處理來得清楚:哪個畫面需要攔截、攔截後要做什麼,都留在該畫面的檔案中,不必回到呼叫端翻找。這也是為什麼這裡用 Category 搭配 optional 協定方法,而不是要求所有畫面都繼承某個自訂的基底類別——後者會限制繼承結構,前者則是零成本的侵入式擴充。