8

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 controller's metrics array and calls its setChartValues() method.

Is there a way I can do that? I can't 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 appreciated, thanks!

McKinley
  • 1,123
  • 1
  • 8
  • 18
Nolan Mulder
  • 81
  • 1
  • 5

1 Answers1

7

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()
Vlad
  • 932
  • 6
  • 18
  • 1
    Thank you for your answer! I could tryout but I just did. I tried to implement the workaround you proposed but it didn't work. You meant to add this under the declaration of the chartVM observable object right? I hope apple will fix this soon... – Nolan Mulder Nov 07 '19 at 10:06
  • @NolanMulder yes under the declaration. Can you provide the code for the `ChartViewModel metrics` declaration? If it is not decorated with @Published, then it won't cause the view to update. – Vlad Nov 11 '19 at 05:30
  • I can confirm that with the `RandomClass` code in there, `updateUIViewController` gets called more often. It's safe to say I would not have found that on my own. – Andrew Duncan Mar 10 '20 at 06:15