簡體   English   中英

如何從子UIViewController轉到父UIViewController,再從那里到另一個子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
  • 我認為您應該首先提出第二條,而不是先解散然后再提出第二條。
  • 當您從第一開始顯示第二個時,然后如果您想回到主菜單,則可以立即解雇2個veiwcontroller,而不會受到任何干擾。

試試吧:

我們可以通過導航控制器調用pushViewControllerpopViewController方法來控制我們提出的控制器。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM