ios 展示一个视图控制器,关闭它并在 Swift 中展示一个不同的控制器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43566414/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Present a view controller, dismiss it and present a different one in Swift
提问by ravelinx
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)
})
But I get an error:
但我收到一个错误:
Warning: Attempt to present <UINavigationController: 0xa40c790> on <IIViewDeckController: 0xa843000> whose view is not in the window hierarchy!
回答by Mike Taverne
The error occurs because you are trying to present SecondController from FirstController after you have dismissed FirstController. This doesn't work:
发生错误是因为您在关闭 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)
})
This problem is very similar to a question I answeredyesterday.
这个问题和我昨天回答的一个问题非常相似。
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)
})