如何在 UINavigationController 中以编程方式显示模态

Sup*_*ngo 2 uinavigationcontroller swift

在我的应用程序中,我有一个 UINavigationController,我正在从中推送和弹出 ViewControllers。在某些时候,我想以模态方式显示 VC(在“下方”显示前一个控制器)。我可以通过在情节提要中设置转场来使其工作,但是我处于需要以编程方式进行操作的地方,而且我似乎无法找到正确的魔法咒语来使其工作。

我看到了几个类似的问题,但它们似乎以模态方式显示 UINavigationController,而不是以模态方式显示 UINavigationController 堆栈上的 VC 之一。

(我在这里放置了一个测试应用程序:https : //github.com/SuperTango/ModalNavController,这就是此代码和图像的来源)

“手册”代码执行以下操作:

@IBAction func goToVC2Tapped(_ sender: Any) {
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let destinationViewController = storyboard.instantiateViewController(withIdentifier: "VC2ViewController") as! VC2ViewController
    destinationViewController.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
    self.navigationController?.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
    self.navigationController?.pushViewController(destinationViewController, animated: true)
}
Run Code Online (Sandbox Code Playgroud)

但它不起作用(请参阅下面 gif 中的第二个转换)。

有效的 segue 设置如下:

转场设置

这个 gif 来自测试应用程序,显示了它如何与 segue 一起工作,但不是手动的。

在此处输入图片说明

有任何想法吗?谢谢!

Kev*_*vin 5

要以模态呈现,您需要使用:

present(destinationViewController, animated: true, completion: { })
Run Code Online (Sandbox Code Playgroud)