用蘋果手機最順手的莫過於右滑返回。但開發中一旦自定義了 leftBarButtonItem,系統的 interactivePopGestureRecognizer 就會失效。本文記錄如何在換掉返回按鈕的同時把手勢找回來。
效果預覽:

從 A push 到 B 時,如果想改的是 B 的返回按鈕文案,可以在 A 裡設置:
self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:nil action:nil];
這種寫法只改文案樣式,不影響手勢。
多數人更習慣在 B 裡自己造按鈕。但一設置 leftBarButtonItem,右滑手勢就沒了。解法是把 interactivePopGestureRecognizer 的 delegate 臨時接管過來:
@interface ViewController () @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
關鍵細節有三處:進入頁面時先備份系統原本的 delegate,離開時原樣還回去,避免影響其他頁面;用 childViewControllers.count > 1 判斷,根控制器不響應右滑,防止側滑後出現空白;兩個手勢代理方法配合,保證與其他手勢共存而不衝突。
以上就是自定義返回按鈕並保留系統滑動返回手勢的完整做法。