首页 > 解决方案 > 从最后一个模态 UINavigtonController UIViewController 在父 UIViewController 中调用 func

问题描述

我像这样展示一个模型 UINavigationController

let flowLayout = UICollectionViewFlowLayout()
let firstViewController = FirstViewController(collectionViewLayout:flowLayout)
let navigationController = UINavigationController(rootViewController: firstViewController)
navigationController.modalPresentationStyle = .fullScreen
present(navigationController, animated: true, completion: nil)

这个 NavigationController 将包含两个 UIViewcontrollers,在最后一个中,当我关闭 NavigationController 时,我想在关闭之前在主控制器中调用一个函数

我知道如何使用协议和委托,但前提是我只使用两个 UIViewController 而不是 UIViewController 和 UINavigationController。

像这样

protocol SecondViewControllerDelegate {
    func someFunction()
}

class SecondViewController: UIViewController {

    var delegate: SecondViewControllerDelegate?

    @objc func myRightSideBarButtonItemTapped(_ sender:UIBarButtonItem!)
    {

        self.delegate?.someFunction()
    }
}

我是否必须创建一个 CustomNavigationController,或者是否有任何其他方式,例如通过所有 ViewControllers 传递委托

标签: swiftuinavigationcontrollermodalviewcontroller

解决方案


您可以编写如下内容:

let flowLayout = UICollectionViewFlowLayout()
let firstViewController = FirstViewController(collectionViewLayout: flowLayout)
firstViewController.delegate = self
let navigationController = UINavigationController(rootViewController: firstViewController)
navigationController.modalPresentationStyle = .fullScreen
present(navigationController, animated: true, completion: nil)

或使用回调而不是委托:

class FViewController: UIViewController {
    var onButtonAction: (() -> Void)?

    @IBAction onButtonTapped(_ sender: Any) {
      onButtonAction?()
    }
}

class SViewController: UIViewController {

    func someMethod() {
      let fVC = FViewController()
      fVC.onButtonAction = {}
      let navigationController = UINavigationController(rootViewController: fVC)
      present(navigationController, animated: true, completion: nil)
    }
}

推荐阅读