Попытка присвоить объекту @EnvironmentObject из дочернего представления родительский объект не удалась, так как EnvironmentObject доступен только для чтения - PullRequest
0 голосов
/ 09 февраля 2020

У меня есть приложение на основе карты, поэтому я хочу иметь свойство приложения для текущей позиции карты.

Я инициализирую его в SceneDelegate

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

I объявить его в 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)

in 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 с текущим координаты.

Текущая позиция объявлена ​​следующим образом

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

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

1 Ответ

1 голос
/ 09 февраля 2020

Полный ответ (дополнено комментарием)

Вы просто изменяете свойства класса, а не пытаетесь создать другой класс. Например:

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

Ошибка:

Невозможно присвоить свойству: свойство currentPosition доступно только для получения

говорит, что Вы не можете присвоить значение напрямую на currentPosition, потому что это @ObservedObject / @EnvironmentObject. Это только свойство gettable.

...