我有下面的代码,我刚刚添加了跟踪模式。
struct LocationInfoView: View {
@State var location: CLLocationCoordinate2D
@State private var mapRegion: MKCoordinateRegion
@State private var trackingMode = MapUserTrackingMode.follow
let markers: [Marker]
init(location: CLLocationCoordinate2D) {
self.location = location
mapRegion = MKCoordinateRegion(center: location, span: MKCoordinateSpan(latitudeDelta: 0.00625, longitudeDelta: 0.00625))
markers = [Marker(location: MapPin(coordinate: location))]
}
var body: some View {
Map(
coordinateRegion: $mapRegion,
showsUserLocation: true,
userTrackingMode: $trackingMode,
annotationItems: markers) { marker in
marker.location
}
.edgesIgnoringSafeArea(.bottom)
}
}
struct Marker: Identifiable {
let id = UUID()
var location: MapPin
}
当我添加MapUserTrackingMode时,我得到Variable 'self.location' used before being initialized
和Variable 'self.mapRegion' used before being initialized
错误。我不明白为什么添加跟踪模式会导致初始化问题。
1条答案
按热度按时间sczxawaw1#
您所得到的错误并不是特别有用,而且由于您在添加
trackingMode
之前所做的事情一开始就不应该真正起作用,这一事实使它更加令人困惑。问题是,如果要在
View
init中初始化@State
变量,必须使用_myVar = State(...)
语法:参见相关:SwiftUI @State var initialization issue