I'd like to implement a basic Map view that will center on the users location when they tap a button, similar to the Apple Maps app. I tried the following, but whenever I tap the button, [SwiftUI] Modifying state during view update, this will cause undefined behavior.
is printed in the console. It seems to me that updating the tracking
state variable is causing the error. However, I'm not sure how else the state variable is meant to be used. The app does behave as intended despite printing the error. Does anyone have any experience with this or know what might be wrong?
struct ContentView: View {
@State var region: MKCoordinateRegion = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 47.3769, longitude: 8.5417), latitudinalMeters: 2000, longitudinalMeters: 2000)
@State var tracking = MapUserTrackingMode.follow
var body: some View {
ZStack {
Map(coordinateRegion: $region, interactionModes: .all, showsUserLocation: true, userTrackingMode: $tracking)
.ignoresSafeArea()
.task {
let locationManager = CLLocationManager()
locationManager.requestWhenInUseAuthorization();
}
Button {
tracking = .follow
} label: {
Image(systemName: tracking == .follow ? "location.fill" : "location")
.padding()
}
.background(.white)
}
}
}