[英]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.