swift 添加MapUserTrackingMode会导致初始化问题

6qqygrtg  于 2022-11-21  发布在  Swift
关注(0)|答案(1)|浏览(117)

我有下面的代码,我刚刚添加了跟踪模式。

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 initializedVariable 'self.mapRegion' used before being initialized错误。我不明白为什么添加跟踪模式会导致初始化问题。

sczxawaw

sczxawaw1#

您所得到的错误并不是特别有用,而且由于您在添加trackingMode之前所做的事情一开始就不应该真正起作用,这一事实使它更加令人困惑。
问题是,如果要在View init中初始化@State变量,必须使用_myVar = State(...)语法:

@State var location: CLLocationCoordinate2D
@State private var mapRegion: MKCoordinateRegion
@State private var trackingMode = MapUserTrackingMode.follow
let markers: [Marker]

init(location: CLLocationCoordinate2D) {
  _location = State(initialValue: location)
  _mapRegion = State(initialValue: MKCoordinateRegion(center: location, span: MKCoordinateSpan(latitudeDelta: 0.00625, longitudeDelta: 0.00625)))
  markers = [Marker(location: MapPin(coordinate: location))]
}

参见相关:SwiftUI @State var initialization issue

相关问题