在模态视图控制器上呈现另一个模态视图控制器

9
我有一个视图控制器VC1,它以全屏模态呈现在其他VC0上方。在我的故事板中,我从VC1到VC2有一个模态转场,也是以全屏呈现的。在我的应用程序中,我可以清楚地看到VC2覆盖在VC1和VC0之上,因为它们的某些视图是透明的。完美。
然而,我要多次重复使用VC2,所以我不想为我的故事板中的每个控制器都创建一个segue,所以我想通过编程方式实现相同的效果。但是,当我在VC1中调用presentViewController:animated:completion来呈现VC2时,当模态转换完成时,VC1的视图消失了。当VC2被解除显示时,当过渡动画完成时,VC1的视图重新出现。
我该如何以编程方式获得与使用故事板segue时相同的效果?
3个回答

20
let newView = self.storyboard!.instantiateViewControllerWithIdentifier("NewViewController") as! NewViewController

newView.modalPresentationStyle = UIModalPresentationStyle.OverFullScreen

self.presentViewController(newView, animated: true, completion: nil)

13

你只能在可见的控制器上进行展示,通常是 rootViewController。但是当有一个模态呈现的控制器时,它会覆盖根控制器,因此你不能使用它。不过你可以在模态控制器上展示,通过访问 rootViewController.presentedViewController 实现。以下是一些代码:

let rootVC = window?.rootViewController
let presentingVC = (rootVC?.presentedViewController ?? rootVC)
presentingVC?.present(myController, animated: true, completion: nil)

你不需要改变 modalPresentationStyle


这对我有用,并且是一个合理的支持答案。谢谢。 - Amber K
对我有用!应该选择它作为这个主题的最佳答案! - Ivan Georgiev
这个答案对我有效,谢谢! - Danny Meng

8

在调用presentViewController:animated:completion之前,您需要将被呈现控制器的modalPresentationStyle属性设置为UIModalPresentationOverFullScreen。请在调用该方法之前设置该属性。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接