在iOS7中,如果使用了UINavigationController,那么系統自帶的附加了一個從屏幕左邊緣開始滑動可以實現pop的手勢。但是,如果自定義了navigationItem的leftBarButtonItem,那么這個手勢就會失效。解決方法有很多種
1.重新設置手勢的delegate
self.navigationController.interactivePopGestureRecognizer.delegate = (id<UIGestureRecognizerDelegate>)self;
2.當然你也可以自己響應這個手勢的事件
[self.navigationController.interactivePopGestureRecognizer addTarget:self action:@selector(handleGesture:)];
我使用了第一種方案,繼承UINavigationController寫了一個子類,直接設置delegate到self。最初的版本我是讓這個gesture始終可以begin
-(BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer{return YES;}
但是出現很多問題,比如說在rootViewController的時候這個手勢也可以響應,導致整個程序頁面不響應;如果在push的同時我觸發這個手勢,那么會導致navigationBar錯亂,甚至crash;push了多層后,快速的觸發兩次手勢,也會錯亂。嘗試了種種方案后我的解決方案是加個判斷,代碼如下,這次運行良好了。
@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;elseself.currentShowVC = viewController;}-(BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer{if (gestureRecognizer == self.interactivePopGestureRecognizer) {return (self.currentShowVC == self.topViewController);}return YES;}@end
  正當竊喜的時候,發現了另一個更高端的解決方案,就是參考2。使用backBarButtonItem
// 統一替換 back item 的圖片[self.navigationController.navigationBar setBackIndicatorImage:[UIImage imageNamed:@"CustomerBackImage"]];[self.navigationController.navigationBar setBackIndicatorTransitionMaskImage:[UIImage imageNamed:@"CustomerBackImage"]];// back item的標題 是 被將要返回的頁面 所控制的,所以如果要改變當前的back item的標題,要在上一個viewcontroller里面設置self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@""style:UIBarButtonItemStylePlaintarget:nilaction:nil];
不過這種方案的缺點是如果你要設置 leftBarButtonItems 來更多的自定義左邊的 items時,手勢又會失效(或者有其他方案我還不知道*—*)。所以最后我又選擇了自己的方法。
參考1 http://www.taofengping.com/2013/12/26/ios7_barbuttonitem_navigation_gesture/
參考2 http://blog.movieos.org/post/63401593182/custom-uinavigationcontroller-back-buttons-under-ios7
新聞熱點
疑難解答