我想通过传递SwiftUI将SwiftUI视图用作子UIView的内容(在我的应用程序中,该视图将位于UIViewController内部)。但是,一旦嵌入到UIView中,SwiftUI视图就不会响应状态更改。
我在下面的代码中创建了简化版,出现了问题。当轻按EmbedSwiftUIView内嵌的Text View时,位于顶部VStack的外部Text View会按预期更新,但EmbedSwiftUIView内嵌的Text View不会更新其状态。
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
或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
}
}