swiftui - UIViewControllerRepresentable 中包含的@Binding 未更新
问题描述
我有一个UIHostingController
包含在 aUIViewControllerRepresentable
中,它包含对绑定的引用。当绑定更改时,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?
}
}
解决方案
以下代码将按需要工作:
我不确定这是否是一种好习惯,因为我对 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)
}
}
我希望这有帮助!
推荐阅读
- pip - 有什么方法可以使用 pip 获取没有版本信息的已安装模块?
- google-cloud-platform - 错误:无法部署资产“webhooks/ActionsOnGoogleFulfillment”
- java - 更改工具栏图标和工具提示 JavaSwing
- c# - Entity Framework Core 3.x 数据库首次设计,其中数据库设计时没有外键
- swift - 在 swift/firebase 项目中,当使用 .observe 而不是使用 SingleEvent 时,是什么导致数组可读?
- postgresql - 序列必须具有与其链接到的表相同的所有者
- ios - 收到此错误:nw_protocol_get_quic_image_block_invoke dlopen libquic failed
- intellij-idea - 如何将 PyCharm 字体设置回默认大小?
- python - DRF 如何测试文件上传?
- python - 有人可以向我解释为什么 pyautogui TypeError: cannot unpack non-iterable NoneType object