ios - 在 Swift 中跨选项卡和 VC 共享数据
问题描述
我有一个带有自定义标签栏控制器的应用程序,以及一个由 stateController 提供支持的数据模型。我想跨选项卡共享模型中的数据。
几个标注:
- 我的应用程序同时使用故事板和程序化(Swift 5)。假设故事板在这里
- 当应用程序加载时,我会检查 userDefaults 以查看它是否是第一个应用程序启动。如果是,firstTimeVC 是 rootVC
- 如果不是,我的 Tab Bar 就是 rootVC。这个逻辑存在于场景委托中
我正在使用依赖注入跨选项卡创建我的数据模型的共享实例。人们建议使用 App / Scene Delegate 将数据模型注入我的 TabBar 和 childVC。问题是,TabBar 并不总是 rootVC。
我的问题是:
- 我可以直接从 TabBar 将我的数据模型注入到 TabBar 的子 VC 中吗?而不是场景代表?
- 如果我使用 Scene Delegate,那么当 TabBar 不是 rootVC(即第一个应用程序启动)时,如何将数据模型注入 TabBar 的 childVC
- 或者 TabBar 是否应该始终是 rootVC,并且我将首次启动检查移动到 childVC 而不是 Scene Delegate
- 这样做的正确方法是什么?
我的第一次应用启动检查(目前在 Scene Delegate 中):
if isFirstLaunch {
rootViewController = "FirstTimeUserViewController"
} else {
rootViewController = "TabBarController"
}
window?.rootViewController = rootViewController
window?.makeKeyAndVisible()
我的依赖注入(目前在场景委托中):
let tabBarController = storyboard.instantiateViewController(withIdentifier: "CustomTabBarController") as! CustomTabBarController
for child in tabBarController.viewControllers ?? [] {
if let top = child as? StateControllerProtocol {
top.setStateController(stateController: stateController)
}
}
我的故事板和 VC 设置的屏幕截图:
解决方案
推荐阅读
- javascript - 无法将数组添加到循环中的另一个对象
- java - 查找一个单词并返回该单词的特定值
- javascript - 当缩略图悬停在一页中的所有产品时替换主图像
- python - 在模型中使用类元时如何修复关系不存在 - 错误?
- php - 检查表中的 id-es
- azure-ad-b2c - Azure AD B2C 自定义策略不尊重 B2C 密码保护配置
- notation - 如何在 BNF 中写一个句子?
- json - 如果 JSON 文件包含未连接的数组,AWS Quicksight 会错误地将导入的 JSON 数字字段留空
- javascript - 仅允许逗号后的空格并使用正则表达式限制文本字段中的特殊字符
- mysql - 如何在 MySQL 语句中捕获空输入值?