iOS开发:下拉关闭模态VC1时如何自动关闭其弹出的VC2?
解决方案:下拉关闭VC1时自动关闭VC2
方法1:通过UIAdaptivePresentationControllerDelegate监听下拉事件
由于VC1是page sheet样式,系统下拉关闭操作会触发presentationControllerDidDismiss:代理方法,可通过这个时机处理VC2的关闭:
- 在VC1的
viewDidLoad中设置自身为presentationController的代理:
- (void)viewDidLoad { [super viewDidLoad]; self.presentationController.delegate = self; }
- 遵守
UIAdaptivePresentationControllerDelegate协议,实现代理方法:
#pragma mark - UIAdaptivePresentationControllerDelegate - (void)presentationControllerDidDismiss:(UIPresentationController *)presentationController { // 关闭VC2,关闭动画设为NO避免和VC1的关闭动画冲突 if (self.presentedViewController) { [self.presentedViewController dismissViewControllerAnimated:NO completion:nil]; } }
方法2:直接调用dismiss关闭整个控制器链
如果是主动触发VC1的关闭(比如按钮点击),可以直接在VC1内调用以下代码,系统会自动关闭所有由VC1 presented的控制器:
[self dismissViewControllerAnimated:YES completion:nil];
此方法适用于主动关闭场景,下拉关闭场景还是方法1更可靠。
原方法无效的原因
你之前重写的viewWillDisappear等生命周期方法,在VC2存在时,下拉操作会被VC2的上下文拦截,系统不会触发VC1的这些方法,直到VC2被手动关闭后才会响应VC1的关闭事件,因此无法捕获到下拉关闭的时机。
内容的提问来源于stack exchange,提问作者ashipma
相关产品推荐
相关产品推荐

