Clambake for iPhone有一個回退按鈕在所有的導航條上.這是一個簡單的沒有文字箭頭.
實現一個自定義按鈕是簡單的.類似這個設置controller 的navigationItem一個leftBarButtonItem.
1 - (void)viewDidLoad 2 { 3 self.navigationItem.leftBarButtonItem = [self backButton]; 4 } 5 6 - (UIBarButtonItem *)backButton 7 { 8 UIImage *image = [UIImage imageNamed:@"back_button"]; 9 CGRect buttonFrame = CGRectMake(0, 0, image.size.width, image.size.height); 10 11 UIButton *button = [[UIButton alloc] initWithFrame:buttonFrame]; 12 [button addTarget:self action:@selector(backButtonPressed) forControlEvents:UIControlEventTouchUpInside]; 13 [button setImage:[UIImage imageNamed:normalImage] forState:UIControlStateNormal]; 14 15 UIBarButtonItem *item; = [[UIBarButtonItem alloc] initWithCustomView:button]; 16 17 return item; 18 }
但是這樣在iOS7上 pop手勢交互就不好使了.我發現了一個輕松解決的辦法.
通過我的beta測試者,我收到了很多關於pop手勢的崩潰日志.
我發現在棧中推入一個controller后,快速向左平滑,將會引起崩潰.
換句話說,如果用戶在推入還在進行的時候立即去點擊返回.那么導航控制器就秀逗了.
我在調試日志里面發現這些:
nested pop animation can result in corrupted navigation bar
經過幾個小時的奮斗和嘗試,我發現可以緩解這個錯誤:
設置手勢的delegate為這個導航控制器
就像Stuart Hall在他的帖子說的那樣,分配了一個手勢交互行為的委托在自定義按鈕顯示的時候.然后,當用戶快速點擊退出的時候,控制器因為手勢發送了一個消息在本身已經被銷毀的時候.
我的解決方案是簡單的讓NavigationController自己成為響應的接受者.最好用一個UINavigationController的子類.
1 @interface CBNavigationController : UINavigationController <UIGestureRecognizerDelegate> 2 @end 3 4 @implementation CBNavigationController 5 6 - (void)viewDidLoad 7 { 8 __weak CBNavigationController *weakSelf = self; 9 10 if ([self respondsToSelector:@selector(interactivePopGestureRecognizer)]) 11 { 12 self.interactivePopGestureRecognizer.delegate = weakSelf; 13 } 14 } 15 16 @end
在轉場/過渡的時候禁用 interactivePopGestureRecognizer
當用戶在轉場的時候觸發一個后退手勢,則各種事件又湊一塊了.導航棧內又成了混亂的.我的解決辦法是,轉場效果的過程中禁用手勢識別,當新的視圖控制器加載完成后再啟用.再次建議使用UINavigationController的子類操作.
1 @interface CBNavigationController : UINavigationController <UINavigationControllerDelegate, UIGestureRecognizerDelegate> 2 @end 3 4 @implementation CBNavigationController 5 6 - (void)viewDidLoad 7 { 8 __weak CBNavigationController *weakSelf = self; 9 10 if ([self respondsToSelector:@selector(interactivePopGestureRecognizer)]) 11 { 12 self.interactivePopGestureRecognizer.delegate = weakSelf; 13 self.delegate = weakSelf; 14 } 15 } 16 17 // Hijack the push method to disable the gesture 18 19 - (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated 20 { 21 if ([self respondsToSelector:@selector(interactivePopGestureRecognizer)]) 22 self.interactivePopGestureRecognizer.enabled = NO; 23 24 [super pushViewController:viewController animated:animated]; 25 } 26 27 #pragma mark UINavigationControllerDelegate 28 29 - (void)navigationController:(UINavigationController *)navigationController 30 didShowViewController:(UIViewController *)viewController 31 animated:(BOOL)animate 32 { 33 // Enable the gesture again once the new controller is shown 34 35 if ([self respondsToSelector:@selector(interactivePopGestureRecognizer)]) 36 self.interactivePopGestureRecognizer.enabled = YES; 37 } 38 39 40 @end