I used the Xcode template to create a Mac App. I then modified ContentView.swift
import SwiftUI
import MapKit
struct ContentView: View {
@State private var region = MKCoordinateRegion(
center: CLLocationCoordinate2D(
latitude: 0.0,
longitude: 0.0),
span: MKCoordinateSpan(
latitudeDelta: 0.5,
longitudeDelta: 0.5))
var body: some View {
Map(coordinateRegion: $region)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
When I run this code, Xcode reports a runtime error:
Modifying state during view update, this will cause undefined behavior.
It is reported on Thread 1.
This is identified with a purple warning in the issue navigator, but there is no indication of the location of the error in the source code editor.
The actual map coordinates don't matter. I get the same error with different coordinates.
- Xcode 13.3.1
- OSX Monterey 12.3.1
- Mac Mini M1
P.S. When I cut the example code above from Xcode and pasted it into this message, it added extra line breaks between each line (which I manually removed). Is there a way to have the code paste as it was in Xcode?
P.P.S. When I listed the software and hardware info, If I don't make it a bulleted list, the ended up being displayed on one line. If I put blank lines between them, the blank lines are displayed. Is there any way to make a vertical list without bullets?
I figured it out. The warning is correct, the examples in Apple's documentation are incorrect. The following is from the DH entry for Map:
struct AppleParkMap: View {
@State private var region = MKCoordinateRegion(
center: CLLocationCoordinate2D(latitude: 37.334_900,
longitude: -122.009_020),
latitudinalMeters: 750,
longitudinalMeters: 750
)
var body: some View {
Map(coordinateRegion: $region)
}
}
This code is very similar to what I originally posted. It generates the same error.
The issue is that the region object passed as a binding to the Map() constructor is part of the view's state. The Map object is modifying the binding as it is updating the view which is trying to update the view's state.
The fix that works is to have the region be part of a ViewModel.
class VM: NSObject, ObservableObject {
@Published var region = MKCoordinateRegion(
center: CLLocationCoordinate2D(latitude: 37.334_900,
longitude: -122.009_020),
latitudinalMeters: 750,
longitudinalMeters: 750
)
}
struct ContentView: View {
@State private var vm = VM()
var body: some View {
Map(coordinateRegion: $vm.region)
}
}
This code works without the issue.