首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >UIViewControllerRepresentable中包含的@Binding不会更新

UIViewControllerRepresentable中包含的@Binding不会更新
EN

Stack Overflow用户
提问于 2020-01-22 10:39:30
回答 1查看 295关注 0票数 2

我有一个包含在UIViewControllerRepresentable中的UIHostingController,它包含对绑定的引用。当绑定更改时,将调用updateUIViewController,但不会自动重新呈现基础视图。如何向嵌入式UIHostingController发出需要更新其内容的信号?

以下是该方案的简化版本。请注意,当步进器更改时,第一个Text会自动更新,但PassthroughView UIViewControllerRepresentable中包含的文本不会自动看到其内容重新呈现。

代码语言:javascript
复制
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?
    }
}
EN

回答 1

Stack Overflow用户

发布于 2020-01-22 23:08:55

以下代码将按预期工作:

我不确定这是否是一个好的实践,因为我对UIKit不是很熟悉。

代码语言:javascript
复制
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)
    }

}

我希望这能帮到你!

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59851875

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档