这篇文章主要为大家详细解析了iOS禁用侧滑返回手势要点,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
项目中可能某些页面返回按钮需要自定义,然后在点击返回按钮时做出某些判断,或者直接pop到根控制器,这时候需要禁用侧滑返回手势,防止它不走判断的代码直接返回上个界面。
网上找了些资料,大致方法有两种,但要注意的点没有提到,容易出错,这里整理下:
需求:A -> B -> C,要求B页面禁用侧滑返回
1. B push到 C,C页面可以侧滑返回;
2. B pop回 A,再从A push D,D要可以侧滑返回。
方法一:
在B页面的生命周期设置如下代码
-(void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
if([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
self.navigationController.interactivePopGestureRecognizer.enabled = NO;
}
}
-(void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
if([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
self.navigationController.interactivePopGestureRecognizer.enabled = YES;
};
}
注意:
1、是在viewDidAppear里面禁用导航的侧滑手势,不要在viewWillAppear中设置!
如果在viewWillAppear中禁用了手势,你会发现B->C之后,在C界面侧滑返回时,APP会进入假死状态。原因是B界面将要出现时,你禁用了侧滑手势,导致C侧滑失败,界面卡住。所以要在B界面出现之后,再禁用侧滑手势。
2、要在viewWillDisappear里面激活导航的侧滑手势,不是viewDidDisappear!
导航是共用的,如果不激活就返回了,其他页面也将无法侧滑返回!而在viewDidDisappear设置激活是无效的,要在页面即将消失时激活。
方法二:
也是在B页面的生命周期设置如下代码。方法一是直接关闭和激活侧滑手势,方法二则是B遵循协议UIGestureRecognizerDelegate,设置侧滑交互代理,重写手势方法。
@property (weak, nonatomic) id<UIGestureRecognizerDelegate> restoreInteractivePopGestureDelegate;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
_restoreInteractivePopGestureDelegate = self.navigationController.interactivePopGestureRecognizer.delegate;
}
-(void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
if([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
self.navigationController.interactivePopGestureRecognizer.delegate = self;
}
}
-(void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
if([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
self.navigationController.interactivePopGestureRecognizer.delegate = _restoreInteractivePopGestureDelegate;
};
}
#pragma mark -UIGestureRecognizerDelegate
-(BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
return NO;
}
这里主要解释下为什么要记录导航的侧滑手势代理:
我们有时候会自定义UINavigationController基类,里面可能已经设置了侧滑手势代理,所以在B界面出现后我们重新设置代理为B,消失前我们要把代理重新改回为原来的。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程学习网。
本文标题为:iOS禁用侧滑返回手势要点解析
基础教程推荐
- Flutter绘图组件之CustomPaint使用详解 2023-05-12
- 解决Android Studio突然不显示logcat日志的问题 2023-02-04
- Android中的webview监听每次URL变化实例 2023-01-23
- IOS 播放系统提示音使用总结(AudioToolbox) 2023-03-01
- IOS应用内跳转系统设置相关界面的方法 2022-11-20
- iOS开发教程之XLForm的基本使用方法 2023-05-01
- Android多返回栈技术 2023-04-15
- Android开发使用RecyclerView添加点击事件实例详解 2023-06-15
- android studio按钮监听的5种方法实例详解 2023-01-12
- Flutter手势密码的实现示例(附demo) 2023-04-11
