@Binding, содержащийся в UIViewControllerRepresentable, не обновляется - PullRequest
0 голосов
/ 22 января 2020

У меня есть UIHostingController, содержащийся в UIViewControllerRepresentable, который содержит ссылку на привязку. Когда привязка изменяется, вызывается 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?
    }
}

1 Ответ

1 голос
/ 22 января 2020

Следующий код будет работать по желанию:

Я не уверен, что это хорошая практика, так как я не очень знаком с 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)
    }

}

Надеюсь, это поможет!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...