iOS 7 為 UINavigationController 加上了一個貼心的互動:從螢幕左緣往右滑,即可 pop 回上一頁。問題是,一旦你自訂了 navigationItem.leftBarButtonItem,這個手勢就會失效。以下整理幾種解法與實作時踩到的坑。
self.navigationController.interactivePopGestureRecognizer.delegate =
(id<UIGestureRecognizerDelegate>)self;
[self.navigationController.interactivePopGestureRecognizer
addTarget:self
action:@selector(handleGesture:)];
我採用第一種方案,寫了一個 UINavigationController 的子類別,直接把 delegate 設為自己。最初的版本讓手勢永遠可以 begin:
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
return YES;
}
結果衍生出一連串問題:
嘗試多種方案後,最後靠一個狀態判斷解決:只有在「目前顯示的控制器確實是頂端那一頁」時才允許手勢啟動。
@interface NavRootViewController : UINavigationController
<UIGestureRecognizerDelegate, UINavigationControllerDelegate>
@property (nonatomic, weak) UIViewController *currentShowVC;
@end
@implementation NavRootViewController
- (id)initWithRootViewController:(UIViewController *)rootViewController {
NavRootViewController *nvc = [super initWithRootViewController:rootViewController];
self.interactivePopGestureRecognizer.delegate = self;
nvc.delegate = self;
return nvc;
}
- (void)navigationController:(UINavigationController *)navigationController
willShowViewController:(UIViewController *)viewController
animated:(BOOL)animated {
}
- (void)navigationController:(UINavigationController *)navigationController
didShowViewController:(UIViewController *)viewController
animated:(BOOL)animated {
if (navigationController.viewControllers.count == 1) {
self.currentShowVC = nil;
} else {
self.currentShowVC = viewController;
}
}
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
if (gestureRecognizer == self.interactivePopGestureRecognizer) {
return (self.currentShowVC == self.topViewController);
}
return YES;
}
@end
關鍵在 currentShowVC:它記錄「畫面切換動畫真正結束後所顯示的那一頁」。手勢觸發時若兩者不一致,代表正在轉場途中,此時回傳 NO 就能避免上述所有錯亂。
// 統一替換返回箭頭圖示
[self.navigationController.navigationBar setBackIndicatorImage:
[UIImage imageNamed:@"CustomerBackImage"]];
[self.navigationController.navigationBar setBackIndicatorTransitionMaskImage:
[UIImage imageNamed:@"CustomerBackImage"]];
// back item 的標題由「上一頁」控制,
// 因此要改當前頁的 back 標題,必須在上一個 view controller 中設定
self.navigationItem.backBarButtonItem =
[[UIBarButtonItem alloc] initWithTitle:@""
style:UIBarButtonItemStylePlain
target:nil
action:nil];
這種做法不需要動到手勢,系統行為完全保留,代價是彈性較低——一旦你改用 leftBarButtonItems 來放多個自訂按鈕,手勢又會失效。所以最後我還是回到自己的實作版本。
如果你只是要換掉返回箭頭的樣式,用 backIndicatorImage 就足夠,別去碰手勢。若必須自訂左側按鈕又不想失去側滑返回,就用 delegate + 狀態判斷的折衷方案,並記得同時處理「轉場進行中」與「已在首頁」這兩個邊界條件。