我有一个包含在UIViewControllerRepresentable中的UIHostingController,它包含对绑定的引用。当绑定更改时,将调用updateUIViewController,但不会自动重新呈现基础视图。如何向嵌入式UIHostingController发出需要更新其内容的信号?
以下是该方案的简化版本。请注意,当步进器更改时,第一个Text会自动更新,但PassthroughView UIViewControllerRepresentable中包含的文本不会自动看到其内容重新呈现。
import SwiftUI
struct ContentView: View {
@State var number = 99
var body: some View {
VStack {
Stepper("Stepper", value: $number)
Text("Direct Value: \(number)")
PassthroughView {
Text("Passthrough Value: \(number)")
}
Spacer()
}.font(.headline)
}
}
struct PassthroughView<V: View> : UIViewControllerRepresentable {
typealias UIViewControllerType = UIHostingController<V>
let content: V
init(@ViewBuilder _ content: () -> V) {
self.content = content()
}
func makeUIViewController(context: UIViewControllerRepresentableContext<PassthroughView<V>>) -> UIViewControllerType {
UIViewControllerType(rootView: content)
}
func updateUIViewController(_ controller: UIViewControllerType, context: UIViewControllerRepresentableContext<PassthroughView<V>>) {
// this is called when the binding changes;
// how to tell the UIHostingController to re-render?
}
}发布于 2020-01-22 23:08:55
以下代码将按预期工作:
我不确定这是否是一个好的实践,因为我对UIKit不是很熟悉。
struct PassthroughView<V: View> : UIViewControllerRepresentable {
typealias UIViewControllerType = UIHostingController<V>
let content: V
init(@ViewBuilder _ content: () -> V) {
self.content = content()
}
func makeUIViewController(context: UIViewControllerRepresentableContext<PassthroughView<V>>) -> UIViewControllerType {
UIViewControllerType(rootView: content)
}
func updateUIViewController(_ controller: UIViewControllerType, context: UIViewControllerRepresentableContext<PassthroughView<V>>) {
// this is called when the binding changes;
// how to tell the UIHostingController to re-render?
controller.rootView = content
}
}
struct ContentView: View {
@State var number = 99
var body: some View {
VStack {
Stepper("Stepper", value: $number)
Text("Direct Value: \(number)")
PassthroughView {
Text("Passthrough Value: \(number)")
}
Spacer()
}.font(.headline)
}
}我希望这能帮到你!
https://stackoverflow.com/questions/59851875
复制相似问题