我有两个以模态方式打开的视图控制器。当第一个VC关闭时,应打开第二个。但是当我关闭第一个时,第二个根本不显示。 有什么问题吗?
我的代码是:
self.dismiss(animated: true) {
let flowVC = LanguageFlowViewController()
self.present(flowVC, animated: true)
}
答案 0 :(得分:3)
您需要从此处提交第一个视图控制器的视图控制器参考。
例如,您的第一个视图控制器X
从此处的视图控制器名称为A
。因此,您需要引用X
来显示B
,因为A
在内存中将不可用。
因此,当您尝试使用self
显示第二个视图控制器时,它什么也不会做。
因此,对于解决方案,将X
视图控制器的引用分配给A
。在类A
中,声明:
var refX: X?
从A
到X
时,请将self
设置为refX
。喜欢:
var aVC = A() // This is temp, you need to instantiate your view controller here.
aVC.refX = self
self.present(aVC, animated: true, completion: nil)
现在,在关闭时,内部视图控制器A
:
var bVC = B() // This is temp, you need to instantiate your view controller here.
self.dismiss(animated: true) {
if self.refX != nil {
self.refX?.present(bVC, animated: true, completion: nil)
}
}
我希望这会对您有所帮助。
答案 1 :(得分:1)
您正在通过调用self.dismiss()
来关闭当前视图控制器。
因此,由于它已从视图层次结构中删除,因此无法再显示任何内容。正如其他人提到的那样,请尝试使用self.presentingViewController
或self.navigationController
(如果它在navigationController上)来呈现新视图。
但是,如果需要最大的灵活性,请创建一个委托协议。创建具有功能presentForChild(viewController: UIViewController)
的协议。在上一个视图显示问题代码所在的视图之前,请给它提供协议的引用。
示例:
protocol ChildPresentDelegate: class {
func presentForChild(vc: UIViewController)
}
class FirstController: UIViewController, ChildPresentDelegate {
func presentForChild(vc: UIViewController) {
present(vc, animated: true, completion: nil)
}
/**
other code
*/
func showControllerAsWasShownInTheQuestion() {
let controller = SecondController()
controller.delegate = self
present(controller, animated: true, completion: nil)
}
}
class SecondController: UIViewController {
weak var delegate: ChildPresentDelegate?
func dismissMySelf() {
self.dismiss(animated: true) {
delegate?.presentForChild(vc: LanguageFlowViewController())
}
}
}
答案 2 :(得分:1)
If you want to open modally ThirdViewController after Dismiss SecondViewController then
you have to create protocol for it.
Like we have three UIViewController(FirstViewController,SecondViewController and
ThirdViewController)
Step 1: We need to create a protocol in SecondViewController as given below code.
protocol DismissedViewProtocal{
func dismissView();
}
class SecondViewController: UIViewController {
var delegate: DismissedViewProtocal?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func dismissSecondViewAction(_sender : AnyObject){
dismiss(animated: true) {
self.delegate?.dismissView();
};
}
Step :2 You need to add protocol in FirstViewController as given below
class FirstViewController: UIViewController,DismissedViewProtocal {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func anAction(_sender : AnyObject){
let flowVC = self.storyboard?.instantiateViewController(withIdentifier:"SecondViewController") as? SecondViewController;
secondVC?.delegate = self;
self.present(secondVC!, animated: true) {
};
}
func dismissView() {
let thirdVC =
self.storyboard?.instantiateViewController(withIdentifier:"ThirdViewController");
self.present(thirdVC!, animated: true) {
};
}
}