[英]Automatically dismiss View Controller in swift 4
假设我有3个标有“A”,“B”和“C”的ViewControllers
。 现在,“A”是窗口的rootViewController
,它以模态方式呈现“B”。 当在“B”中点击按钮时,应该立即模态地呈现C并自动解除“B”。 我怎样才能做到这一点? 我在StackOverflow中看到了所有示例,但它们无法正常工作
@IBAction func proceedBtnTapped(_ sender: Any) {
weak var pvc = self.presentingViewController
let vc = ThirdViewController()
pvc?.present(vc, animated: true, completion: { [weak self] in
self?.dismiss(animated: true, completion: nil)
})
}
这是我的代码。 有帮助吗?
首先关闭b视图控制器,然后在A上显示c视图控制器。
尝试这个。
let vc = ThirdViewController()
let navVC = UINavigationController(rootViewController: vc)
if let parent = self.presentingViewController{
self.dismiss(animated: true){
parent.present(navVC, animated: true)
}
}
如果你使用segue
然后使用' Unwind segue
'
为此编写“A视图控制器”中给出的代码
@IBAction func unwindToThisViewController(segue: UIStoryboardSegue) {
self.performSegue(withIdentifier: "YourSegueForC_VeiwController", sender: nil)
}
在B_viewcontroller中,按下按钮调用'Unwind segue'。 然后解雇B_VC,然后C_VC出现在A_VC上。
注意: - 任何View_controler上只有一个View_controler。 如果要添加另一个,请从该View控制器中删除或关闭另一个ViewController。
感谢您的帮助,最后我使用委托和协议完成了这项工作。 我们需要在SecondViewController中创建协议,我们必须在FirstViewController中使用该协议。
// Declare protocol and variable delegate in SecondViewController
protocol dismissVC {
func presentVC()
}
var delegateVC: dismissVC? = nil
// Call that protocol in FirstViewController
class FirstViewController: UIViewController, dismissVC {
func presentVC() {
let pickVc = UIStoryboard(name:"Main", bundle:
nil).instantiateViewController(withIdentifier: "third-VC")
as! ThirdViewController
pickVc.modalPresentationStyle = .custom
present(pickVc, animated: true, completion: nil)
}
}
// Action method in SecondViewController
@IBAction func proceedBtnTapped(_ sender: Any) {
self.dismiss(animated: true) {
self.delegateVC!.presentVC()
}
// and at last call that delegate when you try to use segue
let SecondVc = UIStoryboard(name:"Main", bundle: nil).instantiateViewController(withIdentifier: "second-VC") as! SecondViewController
Vc.modalPresentationStyle = .custom
Vc.delegateVC = self // add delegate here
self.present(Vc, animated: true, completion: nil)
})
// At last call delegate
yourVc.delegateVC = self
使用委托模式EX:UIImagePickerViewControll
class A:UIViewController, BDelegate {
@IBAction func onOpenBController(_ sender:Any) {
let bVC = B()
bVC.delegate = self
present(bVC, animated: true, completion: nil)
}
func bControllerDidSelect(_ controller: B) {
controller.dismiss(animated: true, completion: nil) //Dismiss B controller
present(C(), animated: true, completion: nil) //Present C controller
}
}
class B:UIViewController {
weak var delegate:BDelegate?
@IBAction func onSomeClickEvent(_ sender:Any) {
delegate?.bControllerDidSelect(self)
}
}
protocol BDelegate: class {
func bControllerDidSelect(_ controller:B)
}
class C:UIViewController {
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.