gpt4 book ai didi

swift - 如何使用 ObservableObject 更新 UIViewRepresentable

转载 作者:行者123 更新时间:2023-12-04 15:06:00 29 4
gpt4 key购买 nike

我正在尝试学习与 SwiftUI 结合,我正在努力如何使用 ObservableObject 更新我的 View (来自 UIKit) (以前的 BindableObject )。显然,问题是方法 updateUIView不会触发 @Published对象发送它已更改的通知。

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)
}
}

如何绑定(bind) locationCoordinates以这样的方式将数组添加到 View 中,实际上每次刷新时都会添加一个新点?

最佳答案

确保您的 ObservedObject不会被多次创建(你只想要一份),你可以把它放在你的 UIViewRepresentable 之外:

import SwiftUI
import MapKit

struct ContentView: View {
@ObservedObject var dataSource = DataSource()

var body: some View {
MyView(locationCoordinates: dataSource.locationCoordinates, value: dataSource.value)
}
}
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 {
var locationCoordinates: [CLLocationCoordinate2D]
var value: Int

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

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

关于swift - 如何使用 ObservableObject 更新 UIViewRepresentable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57478134/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com