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