【问题标题】:How do I bridge between SwiftUI and UIKit如何在 SwiftUI 和 UIKit 之间架起桥梁
【发布时间】:2022-11-13 21:47:01
【问题描述】:

我目前正在开发一个同时使用 swiftUI 和 UIKit 的项目。我制作了一个 ViewController 来处理,但现在我想将它用作原始内容视图中的导航链接。

我尝试的第一件事是正常的

NavigationLink{
                    ViewController()
                } label: {
                    Text("XXX")
                }

但我得到了这两个错误:

Generic struct 'NavigationLink' requires that 'ViewController' conform to 'View'

Static method 'buildBlock' requires that 'ViewController' conform to 'View'

我发现这个 this 帖子说要使用结构,但这也不起作用,我也遇到了其他错误。

那么我怎样才能有效地将我的视图控制器用作导航链接

【问题讨论】:

标签: swift swiftui uikit uiviewcontrollerrepresentable


【解决方案1】:

您确实需要将视图控制器包装在符合 UIViewControllerRepresentable 协议的 SwiftUI 结构中。这允许您在 SwiftUI 视图层次结构中使用 UIKit 视图控制器。

有一个非常相似的协议,UIViewRepresentable,它适用于不是控制器的 UIKit 视图——它的工作方式几乎完全相同。

因此,如果您的 UIKit 视图控制器名为 MyViewController,我们可以将其包装在一个名为 MyView 的 Swift 视图中。我们必须实现两种方法:

struct MyView: UIViewControllerRepresentable {
  // autocomplete will give a return value of `some UIViewController`
  // but if you replace that with your controller's class name, it
  // makes everything clearer
  func makeUIViewController(context: Context) -> MyViewController {
    // do basic setup in here
    return MyViewController()
  }

  func updateUIViewController(
    // you have to specify your UIKit class name here too
    _ uiViewController: MyViewController,
    context: Context
  ) {
    // do the main configuration of your view controller in here,
    // especially if there's SwiftUI state you need the controller
    // to react to
    /// 
    // You don't have to do anything in this method, but you still have
    // to include it. Leave it empty if you're not configuring anything
  }
}

这就是你要让你的控制器版本在 SwiftUI 的视图层次结构中工作所要做的一切。您必须记住直接使用 SwiftUI 包装器而不是 UIKit 视图控制器,例如:

NavigationLink{
  MyView()
} label: {
  Text("XXX")
}

如果您需要将信息传递给视图控制器以进行设置,让它响应 SwiftUI 状态的变化,或者如果您想要根据控制器中的事件或操作更新状态,则还有更多工作要做。但我认为这超出了你的问题范围。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多