SwiftUI View 在嵌入 UIView 时不会更新其状态(使用 UIHostingController)

Dam*_*amo 9 uiview ios swift swiftui uiviewrepresentable

我想通过传递 SwiftUI 来使用 SwiftUI 视图作为子 UIView(在我的应用程序中将在 UIViewController 中)的内容。然而,一旦嵌入到 UIView 中,SwiftUI 视图就不会响应状态更改。

我在下面创建了有问题的代码的简化版本。当点击嵌入在 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>>) {

    }
}
Run Code Online (Sandbox Code Playgroud)

Sil*_*nce 15

更新视图或视图控制器中的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
    }
}
Run Code Online (Sandbox Code Playgroud)