![](/img/trans.png)
[英]calling a parent UIViewController method from a child UIViewController
[英]How to go from child UIViewController to parent UIViewController and from there to another child UIViewController
我有一個父UIViewController( MainVC
)。 從那里,我有2個segue到2個UIViewControllers: FirstVC
(標識符: goFirstVC
)和SecondVC
(標識符: goSecondVC
)在FirstVC
我有一個按鈕Save
,當我單擊它時,我想關閉FirstVC
並繼續SecondVC
。
這是我的代碼:
@IBAction func saveBtnTapped(_ sender: UIButton) {
//navigationController?.popViewController(animated: true)
let destinationController = self.storyboard?.instantiateViewController(withIdentifier: "goSecondVC") as! SecondVC
let presentingVC = self.presentingViewController
self.dismiss(animated: false, completion: { () -> Void in
presentingVC!.present(destinationController, animated: true, completion: nil)
})
}
這是我的問題的設計:
您可以使用setViewControllers
保留僅父級和SecondVC
let destinationController = self.storyboard?.instantiateViewController(withIdentifier: "goSecondVC") as! SecondVC
self.navigationController?.setViewControllers([self.navigationController!.viewControllers.first!,destinationController], animated: true)
有很多方法,但通用方法之一是使用委托和協議。 在您的課程中使用以下代碼。
在第一個VC中添加以下代碼
protocol SecondVCDelegate : AnyObject {
func goToSecondVC()
}
class FirstVC: UIViewController {
var Delegate : SecondVCDelegate!
@objc func save() {
Delegate.goToSecondVC()
}
}
//In second view
在MinVC中添加以下代碼
class MainVC: UIViewController {
override func viewDidAppear() {
self.performSegue(withIdentifier: <yourSegueIdentifierToFirstVC>, sender: nil)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == <yourSegueIdentifierToFirstVC> {
let cont = segue.destination as! FirstVC
cont.Delegate = self
}
}
}
extension MainVC : SecondVCDelegate {
func goToSecondVC() {
self.performSegue(withIdentifier: <yourSegueIdentifierToSecondVC>, sender: nil)
}
}
//This is MainVC
試試吧:
我們可以通過導航控制器調用pushViewController
和popViewController
方法來控制我們提出的控制器。
FirstVC.navigationController?.popViewController(animated: animated) // pops the top view controller
self.navigationController?.pushViewController(SecondVC, animated: true) // Pushes a view controller onto navigation's stack of controllers
在您的情況下:
let destinationController = self.storyboard?.instantiateViewController(withIdentifier: "goSecondVC") as? SecondVC
self.navigationController?.popViewController(animated: animated)
self.navigationController?.pushViewController(destinationController, animated: true)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.