gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 15:23:12 25 4
gpt4 key购买 nike

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

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

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>>) {

}
}

最佳答案

更新 updateUIView 中的 View 或 View Controller 或 updateUIViewController功能。在这种情况下,使用 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
}
}

关于ios - SwiftUI View 在嵌入 UIView 时不更新其状态(使用 UIHostingController),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60540825/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com