解雇一个UINavigationController并呈现另一个UINavigationController

3
我有两个视图控制器,ViewControllerAViewControllerB,它们都嵌入在一个 UINavigationController 中。 ViewControllerA 有一个 UICollectionView 来显示图片。
当相机图标位于索引0并选择了 UICollectionViewCell 时,应该关闭 ViewControllerA 并显示 ViewControllerB。同时,还有一个 ViewController 以模态方式呈现 ViewControllerA
这是我的实现,但只能关闭 ViewControllerA,没有其他任何反应。
let controller = self.storyboard?.instantiateViewControllerWithIdentifier("cameraViewController") as! UINavigationController
        self.dismissViewControllerAnimated(true, completion: { () -> Void in
            self.presentingViewController?.presentViewController(controller, animated: true, completion: nil)
        })

presentingViewController 是空的吗? - Jojodmo
它没有抛出任何错误。我通过添加断点进行了调试。它运行了代码,只是没有对其做出反应。 - user3994005
https://dev59.com/2njZa4cB1Zd3GeqPjuhG?rq=1 - Rahul Patel
如果它是nil,那么它不会抛出错误,因为你正在使用self.presentingViewController?而不是self.presentingViewController!。如果它是nil,那很可能是问题的原因 - 尝试打印self.presentingViewController并查看结果。 - Jojodmo
2个回答

2

当视图控制器被解散时,我猜测self已经被释放了,所以self.presentingViewController?也变成了nil。在解散操作发生之前,我会创建一个对呈现视图控制器的强引用:

let presentingViewController = self.presentingViewController
self.dismissViewControllerAnimated(true) { completed in
  if completed {
    presentingViewController?.presentViewController(controller, animated: true, completion: nil)
  }
}

另外,请确保首先 self.presentingViewController 不是 nil


在某个地方看到过这个,但是忽略了它会导致问题。谢谢。 - user3994005

0

没有任何操作发生的原因是因为 self.presentingViewController? 为空。

如果你使用了self.presentingViewController!,则会出现一个错误,指出在解包可选值时意外地发现了nil,应该始终避免这种情况。

你正确地使用了self.presentingViewController?而不是self.presentingViewController!,因为它更加安全,但为了修复这个问题,你必须确保self.presentingViewController?不为空。

let presenting = self.presentingViewController

self.dismissViewControllerAnimated(true, completion: {() -> Void in
    presenting?.presentViewController(controller, animated: true, completion: nil)
})

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