Swift 如何使用ObserveObject更新UIViewRepresentable

Swift 如何使用ObserveObject更新UIViewRepresentable,swift,uikit,mapkit,swiftui,combine,Swift,Uikit,Mapkit,Swiftui,Combine,我正在尝试学习如何与SwiftUI结合,我正在努力使用observeObject(以前的BindableObject)更新我的视图(从UIKit)。问题是,很明显,一旦@Published对象发送了它被更改的通知,方法updateUIView将不会触发 class DataSource: ObservableObject { @Published var locationCoordinates = [CLLocationCoordinate2D]() var value: Int

我正在尝试学习如何与SwiftUI结合,我正在努力使用
observeObject
(以前的
BindableObject
)更新我的视图(从UIKit)。问题是,很明显,一旦
@Published
对象发送了它被更改的通知,方法
updateUIView
将不会触发

class DataSource: ObservableObject {
    @Published var locationCoordinates = [CLLocationCoordinate2D]()
    var value: Int = 0

    init() {
        Timer.scheduledTimer(withTimeInterval: 3, repeats: true) { timer in
            self.value += 1
            self.locationCoordinates.append(CLLocationCoordinate2D(latitude: 52, longitude: 16+0.1*Double(self.value)))
        }
    }
}

struct MyView: UIViewRepresentable {
    @ObservedObject var dataSource = DataSource()

    func makeUIView(context: Context) -> MKMapView {
        MKMapView(frame: .zero)
    }

    func updateUIView(_ view: MKMapView, context: Context) {
        let newestCoordinate = dataSource.locationCoordinates.last ?? CLLocationCoordinate2D(latitude: 52, longitude: 16)
        let annotation = MKPointAnnotation()
        annotation.coordinate = newestCoordinate
        annotation.title = "Test #\(dataSource.value)"
        view.addAnnotation(annotation)
    }
}

如何将
locationCoordinates
数组绑定到视图,以便在每次刷新时添加一个新点?

为了确保您的
ObservedObject
不会被多次创建(您只需要一个副本),您可以将其放在
UIViewRepresentable
之外:

导入快捷界面
导入地图套件
结构ContentView:View{
@ObservedObject var dataSource=数据源()
var body:一些观点{
MyView(locationCoordinates:dataSource.locationCoordinates,值:dataSource.value)
}
}
类数据源:ObserveObject{
@已发布的变量位置坐标=[CLLocationCoordinate2D]()
变量值:Int=0
init(){
Timer.scheduledTimer(withTimeInterval:3,repeats:true){Timer in
self.value+=1
self.locationCoordinates.append(CLLocationCoordinate2D(纬度:52,经度:16+0.1*Double(self.value)))
}
}
}
结构MyView:UIViewRepresentable{
变量位置坐标:[CLLocationCoordinate2D]
var值:Int
func makeUIView(上下文:context)->MKMapView{
MKMapView(帧:.0)
}
func updateUIView(view:MKMapView,context:context){
打印(“有人叫我!”)
设newestCoordinate=locationCoordinates.last??CLLocationCoordinate2D(纬度:52,经度:16)
let annotation=MKPointAnnotation()
annotation.coordinate=newest坐标
annotation.title=“测试(值)”
view.addAnnotation(注释)
}
}

这个解决方案对我来说很有效,但是对于EnvironmentObject,我宁愿用另一个东西(一个交互器)注入模型,它不从View类继承。有没有其他方法可以在不创建从视图继承的结构的情况下观察它?您所做的基本上是将其包装起来,虽然它确实有效,但它并没有显示出修复UIViewRepresentable问题本身的能力。此外,我认为您的解决方案不会修复多次创建ObservedObject的问题。UIViewRepresentable在这里和那里只创建了一次,因此不会多次创建。如果你的意思是一旦视图被重新创建,它就会被重新创建,那么在这两种情况下都会发生。是的,我有同样的问题,唯一的解决办法是将我的数据源保存在环境中,否则它会被重新创建,不管我把它放在哪里。你找到了一种不把它拉出的方法吗?