0

我有一个基于地图的应用程序,所以我想为地图的当前位置提供一个应用程序范围的属性。

我在 SceneDelegate 中初始化它

    let currentPosition = CurrentPosition()
    let mainView = MainView(appState: AppState(), selectedWeatherStation: nil).environmentObject(currentPosition)

我已将其声明MainView@EnvironmentObject

struct MainView: View {
    @State var appState: AppState
    @State var selectedWeatherStation: WeatherStation? = nil

    @EnvironmentObject var currentPosition: CurrentPosition

我把它注射到我的UIViewRepresentable孩子身上

 MapView(weatherStations: $appState.appData.weatherStations,
                    selectedWeatherStation: $selectedWeatherStation).environmentObject(currentPosition)
                    .edgesIgnoringSafeArea(.vertical)

MapView

struct MapView: UIViewRepresentable {
    @Binding var weatherStations: [WeatherStation]
    @Binding var selectedWeatherStation: WeatherStation?

    @EnvironmentObject var currentPosition: CurrentPosition

我有一个最终的子类

final class Coordinator: NSObject, MKMapViewDelegate {
        @EnvironmentObject var currentPosition: CurrentPosition

它充当我的地图视图代表,我想在其中更新currentPosition

  func mapViewDidChangeVisibleRegion(_ mapView: MKMapView) {
            currentPosition = CurrentPosition(northEast: mapView.northEastCoordinate, southWest: mapView.southWestCoordinate)
        }

但是这个作业 currentPosition = CurrentPosition(northEast: mapView.northEastCoordinate, southWest: mapView.southWestCoordinate) 会抛出一个错误 Cannot assign to property: 'currentPosition' is a get-only property ,我真的不知道我做错了什么。

目的是每次用户移动地图时更新位置,以便我可以使用当前坐标向我的 API 执行请求。

CurrentPosition 声明如下

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

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

1 回答 1

1

完整答案(从评论扩展)

您只需更改类的属性,而不是尝试创建另一个类。像这样:

func mapViewDidChangeVisibleRegion(_ mapView: MKMapView) {
    currentPosition.northEast = mapView.northEastCoordinate
    currentPosition.southWest = mapView.southWestCoordinate
}

错误:

无法分配给属性:“currentPosition”是一个只能获取的属性

是说您不能直接将值分配给currentPosition,因为它是@ObservedObject/ @EnvironmentObject。它只是一个可获取的属性。

于 2020-02-09T11:47:57.213 回答