【发布时间】:2019-12-20 00:48:11
【问题描述】:
我正在尝试学习与 SwiftUI 结合,我正在努力如何使用 ObservableObject(以前的 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 数组绑定到视图,这样每次刷新时实际上都会添加一个新点?
【问题讨论】:
-
你有没有找到不拔掉它的方法?
标签: swift uikit mapkit swiftui combine