iOS左滑手势失效
iOS左滑手勢失效
iOS7之后,蘋果優化了一個小功能,就是對于UINavagationController堆棧里的UIViewController,只要輕輕在視圖控制器的左邊緣右滑一下,該視圖控制器就會pop出棧(前提當然是對于非根視圖控制器而言)。實現方法很簡單,一句話搞定:
self.navigationController.interactivePopGestureRecognizer.enabled = YES;事實上對于一個視圖控制器而言,該屬性的默認值即為YES,因此不設置也能實現右滑pop的功能。
然而這個功能很有局限性,因為它不允許當前視圖控制器自定義了leftBarButtonItem,一旦自定義,右滑功能就會失效。這里有一個方法:
self.navigationController.interactivePopGestureRecognizer.delegate = nil;設置代理為nil之后即便自定義了leftBarButtonItem也可以右滑pop。
或者,把手勢的許可打開 也可:
self.navigationController.interactivePopGestureRecognizer.enabled = YES ;事實上如果自定義了leftBarButtonItem,常用的做法是重新設置代理:
- (void)viewDidAppear:(BOOL)animated{self.navigationController.interactivePopGestureRecognizer.delegate = (id)self; }然后實現手勢協議即可:
#pragma mark - UIGestureRecognizerDelegate - (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer*)gestureRecognizer{//判斷是否為rootViewControllerif (self.navigationController && self.navigationController.viewControllers.count == 1) {return NO;}return YES; }不過呢,如果我們自定義的返回button只是文字或圖片的話,這樣設置就可以,不會失效
UIBarButtonItem *item = [[UIBarButtonItem alloc]init];item.title = @"";self.navigationItem.backBarButtonItem = item;如果是要自定義view的當作button的話,就要用leftBarButtonItem設置,并用上述講的防止手勢失效的方案.
有朋友提出以上方式在多次滑動之后會導致界面假死,這里再給出一種解決方案:
在所有除一級頁面之外的頁面的viewDidAppear和viewWillDisappear中加入以下代碼:
- (void)viewWillDisappear:(BOOL)animated {[super viewWillDisappear:animated];//代理置空,否則會閃退if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {self.navigationController.interactivePopGestureRecognizer.delegate = nil;} } - (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; //開啟iOS7的滑動返回效果 if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) { //只有在二級頁面生效 if ([self.navigationController.viewControllers count] == 2) { self.navigationController.interactivePopGestureRecognizer.delegate = self; } } }在UINavigationController的delegate中實現以下方法:
- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated { //開啟滑動手勢if ([navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {navigationController.interactivePopGestureRecognizer.enabled = YES;} }在pushviewcontroller之前加入以下代碼:
//在切換界面的過程中禁止滑動手勢,避免界面卡死 if ([_currentNav respondsToSelector:@selector(interactivePopGestureRecognizer)]) {_currentNav.interactivePopGestureRecognizer.enabled = NO; } [_currentNav pushViewController:viewController animated:YES];即可在實現滑動返回的同時,避免界面卡死的問題。
posted @ 2016-11-13 14:59 洛洛愛吃肉 閱讀( ...) 評論( ...) 編輯 收藏總結
- 上一篇: 科维的时间管理法—《可以量化的管…
- 下一篇: 条形的码