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; }
然后实现手势协议即可:
#pragmamark-UIGestureRecognizerDelegate -(BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer*)gestureRecognizer{ //判断是否为rootViewController if(self.navigationController&&self.navigationController.viewControllers.count==1){ returnNO; } returnYES; }
不过呢,如果我们自定义的返回button只是文字或图片的话,这样设置就可以,不会失效
UIBarButtonItem*item=[[UIBarButtonItemalloc]init]; item.title=@""; self.navigationItem.backBarButtonItem=item;
如果是要自定义view的当作button的话,就要用leftBarButtonItem设置,并用上述讲的防止手势失效的方案.
有朋友提出以上方式在多次滑动之后会导致界面假死,这里再给出一种解决方案:
在所有除一级页面之外的页面的viewDidAppear和viewWillDisappear中加入以下代码:
-(void)viewWillDisappear:(BOOL)animated{ [superviewWillDisappear:animated]; //代理置空,否则会闪退 if([self.navigationControllerrespondsToSelector:@selector(interactivePopGestureRecognizer)]){ self.navigationController.interactivePopGestureRecognizer.delegate=nil; } } -(void)viewDidAppear:(BOOL)animated{ [superviewDidAppear:animated]; //开启iOS7的滑动返回效果 if([self.navigationControllerrespondsToSelector:@selector(interactivePopGestureRecognizer)]){ //只有在二级页面生效 if([self.navigationController.viewControllerscount]==2){ self.navigationController.interactivePopGestureRecognizer.delegate=self; } } }
在UINavigationController的delegate中实现以下方法:
-(void)navigationController:(UINavigationController*)navigationControllerdidShowViewController:(UIViewController*)viewControlleranimated:(BOOL)animated{ //开启滑动手势 if([navigationControllerrespondsToSelector:@selector(interactivePopGestureRecognizer)]){ navigationController.interactivePopGestureRecognizer.enabled=YES; } }
在pushviewcontroller之前加入以下代码:
//在切换界面的过程中禁止滑动手势,避免界面卡死 if([_currentNavrespondsToSelector:@selector(interactivePopGestureRecognizer)]){ _currentNav.interactivePopGestureRecognizer.enabled=NO; } [_currentNavpushViewController:viewControlleranimated:YES];
即可在实现滑动返回的同时,避免界面卡死的问题。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。