我有一个基于地图的应用程序,所以我想为地图的当前位置提供一个应用程序范围的属性。
我正在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
作为我的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
}
}
答案 0 :(得分:1)
完整答案(从评论扩展)
您只需更改类的属性,而不是尝试制作另一个类。像这样:
func mapViewDidChangeVisibleRegion(_ mapView: MKMapView) {
currentPosition.northEast = mapView.northEastCoordinate
currentPosition.southWest = mapView.southWestCoordinate
}
错误:
无法分配给属性:“ currentPosition”是仅获取属性
表示不能将值 直接分配给currentPosition
,因为它是@ObservedObject
/ @EnvironmentObject
。这只是一个可获取的属性。