呈现一个视图控制器,将其关闭,然后在Swift中呈现一个不同的视图控制器 [英] Present a view controller, dismiss it and present a different one in Swift
问题描述
因此,我有一个根视图控制器,该控制器具有一个按钮,当用户按下该按钮时,将显示另一个视图控制器.第二个控制器具有一个关闭选项,该选项仅返回到根视图控制器,还有一个按钮,当用户触摸它时,该按钮将关闭当前视图控制器,因此它又回到了根视图控制器,并显示另一个按钮.转到我使用的第一个控制器:
So I have a root view controller that has a button that when the user pushes it, another view controller is presented. This second controller has a dismiss option that just comes back to the root view controller and a button that when the user touches it dismisses the current view controller so it goes back to the root view controller for a second and presents another one. Going to the first controller I use:
let vc = FirstController()
self.present(vc, animated: true, completion: nil)
然后在另一个视图控制器中,我选择仅关闭的按钮,然后执行此操作.
And when in the other view controller I select the button that only dismisses I do this.
self.dismiss(animated: true, completion: nil)
因此,对于需要关闭并显示另一个控制器的第二个控制器,我尝试了以下操作:
So for the second controller that needs to dismiss and present another one I have tried the following:
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!
推荐答案
发生此错误是因为您在关闭FirstController之后尝试从FirstController中显示SecondController.这不起作用:
The error occurs because you are trying to present SecondController from FirstController after you have dismissed FirstController. This doesn't work:
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)
})
此问题与我昨天回答.
针对您的情况进行了修改,我建议这样做:
Modified for your scenario, I would suggest this:
weak var pvc = self.presentingViewController
self.dismiss(animated: true, completion: {
let vc = SecondController()
pvc?.present(vc, animated: true, completion: nil)
})
这篇关于呈现一个视图控制器,将其关闭,然后在Swift中呈现一个不同的视图控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!