我有一个基于地图的应用程序,所以我想为地图的当前位置提供一个应用程序范围的属性。
我在 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
}
}