【问题标题】:SwiftUI View not updating its state when embedded in UIView (using UIHostingController)SwiftUI View 在嵌入 UIView 时不更新其状态(使用 UIHostingController)
【发布时间】:2020-06-17 19:36:55
【问题描述】:

我想通过传递 SwiftUI 将 SwiftUI 视图用作子 UIView(在我的应用程序中位于 UIViewController 内)的内容。但是,SwiftUI 视图一旦嵌入到 UIView 中,就不会响应状态变化。

我在下面创建了有问题的代码的简化版本。 当点击嵌入在 EmbedSwiftUIView 中的文本视图时,顶部 VStack 的外部文本视图会按预期更新,但嵌入在 EmbedSwiftUIView 中的文本视图不会更新其状态。

struct ProblemView: View {

    @State var count = 0

    var body: some View {
        VStack {
            Text("Count is: \(self.count)")
            EmbedSwiftUIView {
                Text("Tap to increase count: \(self.count)")
                    .onTapGesture {
                        self.count = self.count + 1
                }
            }
        }
    }
}

struct EmbedSwiftUIView<Content:View> : UIViewRepresentable {

    var content: () -> Content

    func makeUIView(context: UIViewRepresentableContext<EmbedSwiftUIView<Content>>) -> UIView {
        let host = UIHostingController(rootView: content())
        return host.view
    }

    func updateUIView(_ uiView: UIView, context: UIViewRepresentableContext<EmbedSwiftUIView<Content>>) {

    }
}

【问题讨论】:

  • 由于UIHostingController 用于在 UIKit 世界中嵌入 SwiftUI 视图,我想知道我是否正确理解了您的问题。如果您的意思是别的,这就是为什么它不使用UIViewRepresentable 更新 - 这可能是解决方案:使用func updateUIView() 挖掘您的 UIKit 并找到您的 UIKit 元素以手动更新。我知道你的 UIKit Representable 中有一个 Text() 。但是,由于 SwiftUI 差异机制,这可能会被排除在更新之外,这可能不会尝试查找嵌入在 UIKit 中的 SwiftUI。希望你明白我的意思。

标签: ios swift uiview swiftui uiviewrepresentable


【解决方案1】:

updateUIViewupdateUIViewController 函数中更新视图或视图控制器。在这种情况下,使用UIViewControllerRepresentable 会更容易。

struct EmbedSwiftUIView<Content: View> : UIViewControllerRepresentable {

    var content: () -> Content

    func makeUIViewController(context: Context) -> UIHostingController<Content> {
        UIHostingController(rootView: content())
    }

    func updateUIViewController(_ host: UIHostingController<Content>, context: Context) {
        host.rootView = content() // Update content
    }
}

【讨论】:

  • 太棒了。我担心更新 rootView 会导致它失去状态,但事实并非如此!完美
猜你喜欢
  • 2019-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多