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{
//判断是否为rootViewController
if (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];
即可在实现滑动返回的同时,避免界面卡死的问题。