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!
Use a UIViewControllerRepresentable instance to create and manage a UIViewController object in your SwiftUI interface. Adopt this protocol in one of your app’s custom instances, and use its methods to create, update, and tear down your view controller.
The makeUIView allows us to set up our representable view ( UIActivityIndicatorView, in our case). It’ll be called only once during the SwiftUI view’s lifecycle. The updateUIView gets triggered whenever its enclosing SwiftUI view changes its state.
ViewBag is a very well known way to pass the data from Controller to View & even View to View. ViewBag uses the dynamic feature that was added in C# 4.0. We can say ViewBag=ViewData + Dynamic wrapper around the ViewData dictionary. Let's see how it is used.
Let us first discuss how to pass data from a ASP.NET MVC View to Controller. There are four ways to pass the data from View to Controller which are explained below: Traditional Approach: In this approach, we can use the request object of the HttpRequestBase class.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With