SwiftUI 中的导航协调器

Har*_*lue 6 navigation ios swift coordinator-pattern swiftui

从历史上看,UIKit我们一直使用协调器模式来处理导航。

启动一个新的应用程序,SwiftUI但不清楚如何处理这个问题。

例如,我们当前的流程是:

  1. 应用程序启动
  2. 应用协调器启动
  3. 加载“开始场景”
  4. 开始场景检查身份验证状态并调用 App Coordinator 上的委托
  5. 应用协调器启动showHomeSceneshowAuthScene

就像是

final class AppCoordinator: BaseCoordinator {

  private(set) var navigationController: UINavigationController?

  init(navigationController: UINavigationController?) {
    self.navigationController = navigationController
  }

  override func start() {
    showStartScene()
  }

  private func showStartScene() {
    let configurator = StartConfigurator()
    let viewController = configurator.create(self)
    navigationController?.setViewControllers([viewController], animated: false)
  }

  private func showHomeScene() {
    let coordinator = HomeCoordinator(self, navigationController: navigationController)
    store(coordinator: coordinator)
    coordinator.start()
  }

  private func showAuthScene() {
    let coordinator = AuthCoordinator(self, navigationController: navigationController)
    store(coordinator: coordinator)
    coordinator.start()
  }

}

extension AppCoordinator: StartSceneDelegate {
  func userNeedsToAuthenticate() {
    showAuthScene()
  }

  func userIsAuthenticated() {
    showHomeScene()
  }
}
Run Code Online (Sandbox Code Playgroud)

但是,由于我们没有使用UIViewController它是如何navigationController?.setViewControllers([viewController], animated: false)工作的?

我们还应该使用 a 进行设置UIHostingController吗?

就像是 - navigationController?.setViewControllers([UIHostingController(rootView: StartView())], animated: false)

这似乎有点奇怪,因为我不相信 SwiftUI 视图会真正使用 a ,UINavigationController因为它们使用NavigationViewNavigationLink

除非UINavigationController真的只是作为一个包装?

我正在考虑@EnvironmentObject在协调器中使用并基于身份验证状态替换协调器中的根视图控制器。