用 iPhone 最順手的莫過於從左側往右滑的返回手勢。但當我們在頁面裡自訂了返回按鈕,這個手勢往往就跟著失效——原因不是手勢壞了,而是它的代理被換掉了。

系統的側滑返回由 navigationController 的 interactivePopGestureRecognizer 負責,而它的 delegate 預設綁在原本的堆疊邏輯上。一旦我們自己設了 leftBarButtonItem,這個辨識器就會被系統判定不該啟用,滑了也沒反應。
如果只是要改文字,最省事的做法是在 push 之前,由來源控制器設定:
self.navigationItem.backBarButtonItem =
[[UIBarButtonItem alloc] initWithTitle:@"王儼"
style:UIBarButtonItemStylePlain
target:nil
action:nil];
這種寫法完全不碰手勢,側滑照樣可用。
若需要自訂樣式,就得在頁面出現時暫時接管手勢代理,離開時再還回去:
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(0, 0, 44, 44);
[button setTitle:@"王儼2" 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 設成 self 而沒在 viewWillDisappear 還原,回到上一頁時手勢就會整個死掉,而且症狀會出現在別的頁面上,很難查。另外記得呼叫 super,否則 UINavigationController 內部的轉場動畫會出現異常。