从最后一个模态 UINavigatonController UIViewController 在父 UIViewController 中调用 func
Posted
技术标签:
【中文标题】从最后一个模态 UINavigatonController UIViewController 在父 UIViewController 中调用 func【英文标题】:call func in parent UIViewController from last modal UINavigatonController UIViewController 【发布时间】:2019-02-08 19:01:36 【问题描述】:我像这样展示一个模型 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 传递委托
【问题讨论】:
【参考方案1】:你可以这样写:
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)
【讨论】:
以上是关于从最后一个模态 UINavigatonController UIViewController 在父 UIViewController 中调用 func的主要内容,如果未能解决你的问题,请参考以下文章