在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?

查看:369
本文介绍了在UIViewControllerRepresentable中,如何将ObservedObject的值传递给视图控制器,并在每次值更改时对其进行更新?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个预订了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 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

我总是可以像以前只使用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 UIViewControllerRepresentableUIViewRepresentable中有一个错误,未调用它.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆