从去年模态UINavigatonController的UIViewController调用FUNC在父母的UIViewController

问题描述 投票:-1回答:1

我提出一个模型的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任何其他方式

swift uinavigationcontroller modalviewcontroller
1个回答
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)
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.