У меня есть приложение на основе карты, поэтому я хочу иметь свойство приложения для текущей позиции карты.
Я инициализирую его в 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
}
}