首页 > 解决方案 > 在 Swift 中跨选项卡和 VC 共享数据

问题描述

我有一个带有自定义标签栏控制器的应用程序,以及一个由 stateController 提供支持的数据模型。我想跨选项卡共享模型中的数据。

几个标注:

我正在使用依赖注入跨选项卡创建我的数据模型的共享实例。人们建议使用 App / Scene Delegate 将数据模型注入我的 TabBar 和 childVC。问题是,TabBar 并不总是 rootVC。

我的问题是:

我的第一次应用启动检查(目前在 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 设置的屏幕截图:

我的故事板和 VC 设置的屏幕截图

标签: iosswiftdependency-injectionuitabbarcontroller

解决方案


推荐阅读