11

我想通过传递 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>>) {

    }
}
4

1 回答 1

5

更新视图或视图控制器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
    }
}
于 2020-05-25T18:16:11.907 回答