gpt4 book ai didi

swiftui - UIViewControllerRepresentable 中包含的@Binding 未更新

转载 作者:行者123 更新时间:2023-12-04 10:42:42 26 4
gpt4 key购买 nike

我有一个 UIHostingController包含在 UIViewControllerRepresentable包含对绑定(bind)的引用。当绑定(bind)改变时,updateUIViewController被调用,但底层 View 不会自动重新渲染。如何向嵌入式 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)
}

}

我希望这有帮助!

关于swiftui - UIViewControllerRepresentable 中包含的@Binding 未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59851875/

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