gpt4 book ai didi

当 ObservableObject 的所有属性更新时通知 SwiftUI

转载 作者:行者123 更新时间:2023-12-03 10:25:18 25 4
gpt4 key购买 nike

我有一个 ObservableObject


class CurrentPosition: ObservableObject {
@Published var northEast = CLLocationCoordinate2D()
@Published var southWest = CLLocationCoordinate2D()


init(northEast: CLLocationCoordinate2D = CLLocationCoordinate2D(), southWest: CLLocationCoordinate2D = CLLocationCoordinate2D()) {
self.northEast = northEast
self.southWest = southWest
}

func updateCoordinates(from mapView: MKMapView) {
self.northEast = mapView.northEastCoordinate
self.southWest = mapView.southWestCoordinate
}
}

我想从 MapView 更新
struct MapView: UIViewRepresentable {
@Binding var weatherStations: [WeatherStation]
@Binding var selectedWeatherStation: WeatherStation?

@EnvironmentObject var currentPosition: CurrentPosition

func makeUIView(context: Context) -> MKMapView {
let map = MKMapView()
map.showsUserLocation = true
map.delegate = context.coordinator
return map
}

func updateUIView(_ uiView: MKMapView, context: Context) {
updateAnnotations(from: uiView)
}

func makeCoordinator() -> Coordinator {
Coordinator(self)
}


final class Coordinator: NSObject, MKMapViewDelegate {
var control: MapView

init(_ control: MapView) {
self.control = control
}

func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
control.currentPosition.updateCoordinates(from: mapView)
}

}
}

并将其传递给 AppState目的
 MapView(weatherStations: $appState.appData.weatherStations,
selectedWeatherStation: $selectedWeatherStation).environmentObject(self.currentPosition)
.edgesIgnoringSafeArea(.vertical).onReceive(currentPosition.objectWillChange) { () in
self.appState.currentPosition = self.currentPosition
}}

进而将其传递给我的 API 客户端
class AppState: ObservableObject {
@Published var appData = AppData(weatherStations: [WeatherStation]())
var currentPosition: CurrentPosition! {
didSet {
api.currentPosition = self.currentPosition
}
}
}

我的问题是每次我的 CurrentPosition 之一都会通过属性得到更新,这意味着它首先在 northEast 时通过得到更新,而不是 southWest得到更新。

当两个都完成更新时,我怎样才能只传递一个?

最佳答案

最简单的方法是使用辅助 struct 将其折叠成一个属性。 ,像这样:

struct MapCoordinateSpan {
let northEast: CLLocationCoordinate2D
let southWest: CLLocationCoordinate2D
}

并修改您的 CurrentPosition看起来像这样:
class CurrentPosition: ObservableObject {
@Published var span: MapCoordinateSpan

init(northEast: CLLocationCoordinate2D = CLLocationCoordinate2D(), southWest: CLLocationCoordinate2D = CLLocationCoordinate2D()) {
self.span = MapCoordinateSpan(northEast: northEast, southWest: southWest)
}

func updateCoordinates(from mapView: MKMapView) {
self.span = MapCoordinateSpan(northEast: mapView.northEastCoordinate, southWest: mapView.southWestCoordinate)
}
}

然后绑定(bind)到 span属性,并从那里提取坐标。

关于当 ObservableObject 的所有属性更新时通知 SwiftUI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60136350/

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