简体   繁体   中英

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

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 updateUIViewController is 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!

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM