swift - 从最后一个模态 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 传递委托
解决方案
您可以编写如下内容:
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)
}
}
推荐阅读
- javascript - 未捕获的 RangeError:日期值在 DateTimeFormat.format() 中不是有限的
- c - 为什么我的碰撞检测不起作用,我的角色从右侧穿过墙壁?(SDL,C)
- web - 我可以隐藏我网站页面的 URL 吗?
- visual-studio-code - 如何修复“异步”“等待”关键字没有突出显示 | VS代码
- algorithm - 行进立方体 - 获得倾斜的表面
- python - Selenium Python 在 Google Colab 中不起作用
- asp.net - 使用带有模式优先方法的 hotchocolate 过滤器
- python - 从 XML 文件创建 DataFrame
- c - 为什么我的动态分配数组只包含一个结果?
- android - 每当我尝试在片段中隐藏工具栏时,应用程序首先更改工具栏标题,然后才隐藏自身