
用 iPhone 最順手的就是那個側滑返回手勢。但作為開發者,我們常常因為各種原因讓系統的滑動返回失效——最典型的就是:用導航欄 push 出一個控制器,然後在裡面自訂了一個返回按鈕。一旦設定了 leftBarButtonItem,系統預設的側滑手勢就跟著消失了。
從 A push 到 B,想自訂 B 的返回按鈕文字,可以在 A 裡面設定:
self.navigationItem.backBarButtonItem =
[[UIBarButtonItem alloc] initWithTitle:@"返回"
style:UIBarButtonItemStylePlain
target:nil
action:nil];
這種寫法不會影響側滑手勢,但只能改文字,沒辦法放自訂圖示或更複雜的檢視。
大多數人會選擇在 B 自己設定按鈕,但這正是手勢失效的原因。修法是把 interactivePopGestureRecognizer 的 delegate 暫時接管過來。
@interface ViewController () <UIGestureRecognizerDelegate>
@property (nonatomic, weak) id <UIGestureRecognizerDelegate> delegate; // 記錄系統原本的代理
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 自定義返回按鈕
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
[button setTitle:@"返回" forState:UIControlStateNormal];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[button addTarget:self action:@selector(back:) forControlEvents:UIControlEventTouchUpInside];
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
}
- (void)back:(UIButton *)button {
[self.navigationController popViewControllerAnimated:YES];
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
if (self.navigationController.viewControllers.count > 1) {
// 先記下系統原本的代理
_delegate = self.navigationController.interactivePopGestureRecognizer.delegate;
// 再把代理改成自己
self.navigationController.interactivePopGestureRecognizer.delegate = self;
}
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
// 離開時把代理還原,避免影響其他頁面
self.navigationController.interactivePopGestureRecognizer.delegate = _delegate;
}
#pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
return self.navigationController.childViewControllers.count > 1;
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer
shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
return self.navigationController.viewControllers.count > 1;
}
@end
這套寫法能運作的核心有兩點:
viewWillAppear 中先把系統原本的 delegate 存起來再換成自己,並在 viewWillDisappear 中還回去。少了還原這一步,其他頁面的手勢行為可能會出現難以追查的異常。gestureRecognizerShouldBegin: 判斷堆疊深度。當這個控制器是整個堆疊的根視圖時,回傳 NO,側滑就不該生效——否則使用者在第一頁右滑會出現畫面空白或閃退。如果專案裡每個頁面都要自訂返回按鈕,建議把這段邏輯抽成一個 BaseViewController 或寫成 UINavigationController 的分類,統一處理代理交換與還原,避免各頁重複實作時漏掉還原步驟。