在UIViewControllerRepresentable中,如何将ObservedObject的值传递给视图控制器,并在每次值更改时对其进行更新? [英] In a UIViewControllerRepresentable, how can I pass an ObservedObject's value to the view controller and update it every time the values changes?
问题描述
我有一个预订了ObservableObject的UIViewControllerRepresentable
结构,如下所示:
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()
}
}
我想这样,当ObservedObject更改时,要么调用updateUIViewController
,要么另一个函数更新视图控制器的metrics
数组并调用它的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
我总是可以像以前只使用UIKit一样来做,但是使用该MVVM模式做起来会更好
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
非常感谢您的帮助!
推荐答案
updateUIViewController
,但是SwiftUI UIViewControllerRepresentable
和UIViewRepresentable
中有一个错误,未调用它.
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.
只需在chartVM
下添加以下内容,它就会开始起作用:
Just add the following under chartVM
and it should start to work:
class RandomClass { }
let x = RandomClass()
这篇关于在UIViewControllerRepresentable中,如何将ObservedObject的值传递给视图控制器,并在每次值更改时对其进行更新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!