Home > Mobile >  Adding MapUserTrackingMode causes issues with initialization
Adding MapUserTrackingMode causes issues with initialization

Time:11-22

I have the following code that I've just added tracking mode to.

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
}

The moment I add the MapUserTrackingMode I get Variable 'self.location' used before being initialized and Variable 'self.mapRegion' used before being initialized errors. I don't understand why adding the tracking mode causes an issue with initialization.

CodePudding user response:

The error you're getting isn't particularly helpful and it's made more confusing by the fact that what you were doing before the addition of trackingMode shouldn't have really worked in the first place.

The issue is that if you're going to initialize @State variables in a View init, you must use the _myVar = State(...) syntax:

@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))]
}

See related: SwiftUI @State var initialization issue

  • Related