项目中可能某些页面返回按钮需要自定义,然后在点击返回按钮时做出某些判断,或者直接pop到根控制器,这时候需要禁用侧滑返回手势,防止它不走判断的代码直接返回上个界面。
网上找了些资料,大致方法有两种,但要注意的点没有提到,容易出错,这里整理下:
需求:A -> B -> C,要求B页面禁用侧滑返回
1. B push到 C,C页面可以侧滑返回;
2. B pop回 A,再从A push D,D要可以侧滑返回。
方法一:
在B页面的生命周期设置如下代码
1
2
3
4
5
6
7
8
9
10
11
12
|
-( 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,设置侧滑交互代理,重写手势方法。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
@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,消失前我们要把代理重新改回为原来的。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持快网idc。
相关文章
- 个人服务器网站搭建:如何选择适合自己的建站程序或框架? 2025-06-10
- 64M VPS建站:能否支持高流量网站运行? 2025-06-10
- 64M VPS建站:怎样选择合适的域名和SSL证书? 2025-06-10
- 64M VPS建站:怎样优化以提高网站加载速度? 2025-06-10
- 64M VPS建站:是否适合初学者操作和管理? 2025-06-10
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
-
2025-05-27 73
-
2025-05-27 70
-
2025-05-25 46
-
2025-05-25 90
-
2025-05-25 26