所以我有一个根视图控制器,当用户按下它时会显示另一个视图控制器。这个第二个控制器有一个关闭选项,它只返回到根视图控制器,当用户触摸它时,它会关闭当前视图控制器,因此它会返回到根视图控制器一秒钟并呈现另一个控制器。转到我使用的第一个控制器:
let vc = FirstController()
self.present(vc, animated: true, completion: nil)
当在另一个视图控制器中时,我选择了只关闭我的按钮。
self.dismiss(animated: true, completion: nil)
因此,对于需要解雇并呈现另一个的第二个控制器,我尝试了以下内容:
self.dismiss(animated: true, completion: {
let vc = SecondController()
self.present(vc, animated: true, completion: nil)
})
但是我收到了一个错误:
Warning: Attempt to present <UINavigationController: 0xa40c790> on <IIViewDeckController: 0xa843000> whose view is not in the window hierarchy!
答案 0 :(得分:37)
发生错误是因为您在解除了FirstController后尝试从FirstController呈现SecondController。这不起作用:
self.dismiss(animated: true, completion: {
let vc = SecondController()
// 'self' refers to FirstController, but you have just dismissed
// FirstController! It's no longer in the view hierarchy!
self.present(vc, animated: true, completion: nil)
})
此问题与昨天的问题answered非常相似。
根据您的方案修改,我建议:
weak var pvc = self.presentingViewController
self.dismiss(animated: true, completion: {
let vc = SecondController()
pvc?.present(vc, animated: true, completion: nil)
})
答案 1 :(得分:0)
只有呈现视图控制器(Root)可以关闭其呈现的视图控制器(第一或第二)。
所以你需要在根视图控制器的类中调用 dismiss(animated:completion:)
,而不是在任何其他类中:
class RootViewController: UIViewController {
func buttonTapped() {
let vc = FirstViewController()
vc.delegate = self
present(vc, animated: true)
}
}
extension RootViewController: FirstViewControllerDelegate {
func firstDidComplete() {
dismiss(animated: true) {
let vc = SecondViewController()
vc.delegate = self
present(vc, animated: true)
}
}
}
extension RootViewController: SecondViewControllerDelegate {
func secondDidComplete() {
dismiss(animated: true) {
let vc = ThirdViewController()
present(vc, animated: true)
}
}
}
// and so on
如果 FirstViewController 呈现其他视图控制器并且您想要它的关闭动画,请按如下方式实现 FirstViewController:
extension FirstViewController: OtherViewControllerDelegate {
func otherDidComplete() {
dismiss(animated: true) {
self.delegate?.firstDidComplete()
}
}
}