In a UIViewControllerRepresentable, how can I pass an ObservedObject's value to the view controller and update it every time the values changes?

雨燕双飞 提交于 2020-06-16 05:28:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!