简体   繁体   English

如何在 SwiftUI 中使用 UINavigationController

[英]how to use UINavigationController in SwiftUI

I am trying to create Coordinator to navigate from Screen1 to Screen2我正在尝试创建Coordinator器以从 Screen1 导航到 Screen2

Here is the example of UIKit这是 UIKit 的示例

class Coordinator: AbstractCoordinator {

    var navigationController: UINavigationController?

    func goToHomeScreen() {
        navigationController?.pushViewController(HomeViewController(coordinator: self), animated: true)
    }

    func start() -> UIViewController {
        self.navigationController = UINavigationController(rootViewController: LoginViewController(coordinator: self))

        return navigationController!
    }
}

This Coordinator is very useful when we are using modular programming.当我们使用模块化编程时,这个 Coordinator 非常有用。 I want to do the same thing in SwiftUI我想在 SwiftUI 中做同样的事情

I know we have to use NavigationView, NavigationLink but I can't understand how should I do in Coordinator我知道我们必须使用 NavigationView、NavigationLink 但我不明白我应该如何在 Coordinator 中使用

Can someone tell me how can I do it?有人可以告诉我该怎么做吗?

For using Coordinator in SwiftUI you need to use two components:要在 SwiftUI 中使用协调器,您需要使用两个组件:

  1. Coordinator View and协调员视图和
  2. Coordinator Object协调员 Object

The coordinator view is part of the view hierarchy and controls the transition logic and the overall view context of its child views.协调器视图是视图层次结构的一部分,并控制其子视图的转换逻辑和整体视图上下文。 The coordinator view requires a coordinator object to create view models and allow communication between different scenes.协调器视图需要协调器 object 来创建视图模型并允许不同场景之间的通信。 Similar to coordinators in UIKit, we can have a reference to the coordinator from view models of child scenes and trigger transition events in the coordinator based on the business logic of the view models.与UIKit中的协调器类似,我们可以从子场景的视图模型中引用协调器,并根据视图模型的业务逻辑在协调器中触发过渡事件。

❓ Why do we split our coordinators into two parts? ❓ 为什么我们将协调员分成两部分? In SwiftUI, we have two different responsibilities to be taken care of by a coordinator: A view's context needs to be controlled by a View that is part of the view hierarchy.在 SwiftUI 中,我们有两个不同的职责需要由协调器负责: 视图的上下文需要由视图层次结构中的视图来控制。 But we do not have control of a view's lifecycle.但是我们无法控制视图的生命周期。 This can be achieved easily with an ObservableObject.这可以通过 ObservableObject 轻松实现。 We can easily pass it around by reference and make it conform to the Identifiable protocol.我们可以很容易地通过引用传递它并使其符合 Identifiable 协议。

You can get more details here: https://quickbirdstudios.com/blog/coordinator-pattern-in-swiftui/您可以在此处获取更多详细信息: https://quickbirdstudios.com/blog/coordinator-pattern-in-swiftui/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM