尝试将 child 视图中的 @EnvironmentObject 分配给 parent 失败,因为 EnvironmentObject 是 read-only

Trying to assign to an @EnvironmentObject from a child view to a parent fails as EnvironmentObject is read-only

我有一个基于地图的应用程序,所以我想要一个 app-wide 属性 作为地图的当前位置。

我正在 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 child

 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

作为我的 mapview 委托,我想在其中更新 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
    }
}

完整答案(从评论中扩展)

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

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

错误:

Cannot assign to property: 'currentPosition' is a get-only property

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