如何通过导航控制器传递委托?

How to pass delegate thru Navtigation Controller?

我有 2 个 VC,它们之间有一个导航控制器。如何将第一屏设置为第二屏的代理?

我尝试了什么:

  1. 从第一个开始显示第二个VC(它在没有导航的情况下显示)
  2. 在导航中设置委托VC viewDidLoad()

第一个VC:

    class MainVC: UIViewController, SecondVCDelegate {
    func passData(text: String) {
        // do stuff
    }
    @IBAction func openNextVC(_ sender: Any) {
        let nextVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "NavVC") as! NavVC
        present(nextVC, animated: true, completion: nil)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

导航控制器:

class NavVC: UINavigationController {  
    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

第二VC:

    protocol SecondVCDelegate {
    func passData(text: String)
    }
    
    class SecondVC: UIViewController {
        var delegate: SecondVCDelegate?
    
        @IBAction func save(_ sender: Any) {
           // do stuff
        }
        override func viewDidLoad() {
            super.viewDidLoad()
        }
    }

这里的主要任务是从导航控制器实例 (navC) 访问第二个视图控制器实例。为此,您必须首先从导航控制器实例 (nextVC) 访问 rootViewController,如下所示:

    let nextVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "NavVC") as! NavVC
    let secondVC = nextVC?.viewControllers.first as? SecondVC
    secondVC.delegate = self 
    present(nextVC, animated: true, completion: nil)

当第二个视图控制器是导航控制器的根时,以上代码适用。如果第二个视图控制器不是 navC 的根控制器,那么您必须迭代控制器以获取第二个视图控制器实例。一旦存在第二个控制器实例,您就可以将委托分配给与下面相同的对象。

    for controller in navC.viewControllers {
        if controller.isKind(of: SecondVC.self) {
           if let secondVc = controller as? SecondVC {
              secondVc.delegate = self
           }
           break
        }
    }

我处理过同样的事情。在 MainVC 上试试这个:

 class MainVC: UIViewController, SecondVCDelegate {
    func passData(text: String) {
        // do stuff
    }
    @IBAction func openNextVC(_ sender: Any) {
        guard let secondController = self.storyboard?.instantiateViewController(withIdentifier: "AddGroupVC") as? AddGroupVC else { return }
        secondController.delegate = { [weak self] in
              print("call your delegates here")
                    
          }
      self.navigationController?.present(secondController, animated: true, completion: nil)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

在第二个视图控制器上,调用 viewWillDisappear 中的委托:

class SecondVC: UIViewController {
        var delegate: SecondVCDelegate?
    
        @IBAction func save(_ sender: Any) {
           // do stuff
      self.dismiss(animated: true, completion: nil)
        }
        override func viewDidLoad() {
            super.viewDidLoad()
        }
 override func viewWillDisappear(_ animated: Bool) {
        
        self.delegate
        
    }
    }