从最后一个模式UINavigatonController UIViewController调用父UIViewController中的func

时间:2019-02-08 19:01:37

标签: swift uinavigationcontroller modalviewcontroller

我像这样展示了一个模型UINavigationController

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

此NavigationController将包含两个UIViewcontroller, 在上一个中,当我关闭NavigationController时,我想在关闭前在主控制器中调用一个函数

我知道如何使用协议和委托来做到这一点,但前提是我仅使用两个UIViewController而不是UIViewController和UINavigationController。

像这样

protocol SecondViewControllerDelegate {
    func someFunction()
}

class SecondViewController: UIViewController {

    var delegate: SecondViewControllerDelegate?

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

        self.delegate?.someFunction()
    }
}

我必须创建一个CustomNavigationController,还是有其他方法,例如,将委托传递给所有ViewControllers

1 个答案:

答案 0 :(得分:0)

您可以编写如下内容:

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)
    }
}