繁体   English   中英

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

[英]SwiftUI View not updating its state when embedded in UIView (using UIHostingController)

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

    }
}

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
    }
}

暂无
暂无

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

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