问题
I have a UIViewControllerRepresentable struct that is subscribed to an ObservableObject, like this:
struct ViewControllerWrapper: UIViewControllerRepresentable {
@ObservedObject var chartVM = ChartViewModel()
typealias UIViewControllerType = ViewController
func makeUIViewController(context: Context) -> ViewController {
let lineChartView = LineChartView()
let vc = ViewController(lineChartView: lineChartView)
return vc
}
func updateUIViewController(_ uiViewController: ViewController, context: Context) {
uiViewController.metrics = chartVM.metrics
uiViewController.setChartValues()
}
}
I would like that, when the ObservedObject changes, either updateUIViewControlleris called, or another function that updates the view controler's metrics array and calls it's setChartValues() method.
Is there a way I can do that? I can't manage to find one
I can always do it as we used to using only UIKit, but it would be much better to do it using that MVVM pattern
Help would be much apreciated, thanks!
回答1:
updateUIViewController should be called when the view model is updated, however there is a bug in SwiftUI UIViewControllerRepresentable and UIViewRepresentable where it is not called.
There is a work around to this by defining a class and creating an instance of it inside the representable.
Just add the following under chartVM and it should start to work:
class RandomClass { }
let x = RandomClass()
来源:https://stackoverflow.com/questions/58635048/in-a-uiviewcontrollerrepresentable-how-can-i-pass-an-observedobjects-value-to