I've read a number of questions about this error that relates to dismissing sheets, but none dealing with SwiftUI's Map. The following code generates this error. Nothing is being updated in the view model. I'm simply passing a binding to a region into the Map initializer. Using a local state variable for region works with no error. I'm running Xcode 14.0. If I remove the @Published property wrapper then the error goes away. So I'm confused as to how the view model should notify the view that the region has changed, perhaps due to location updates.
import SwiftUI
import MapKit
class MM : ObservableObject {
@Published var region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 51.507222, longitude: -0.1275), span: MKCoordinateSpan(latitudeDelta: 0.5, longitudeDelta: 0.5))
}
struct SimpleMap: View {
@ObservedObject var mm = MM()
@State private var region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 51.507222, longitude: -0.1275), span: MKCoordinateSpan(latitudeDelta: 0.5, longitudeDelta: 0.5))
var body: some View {
//Error
Map(coordinateRegion: $mm.region)
//No Error
//Map(coordinateRegion: $region)
}
}
StateObject
instead ofObservedObject
– MandeObservableObject
object initialised with@StateObject
and when you pass it to other views, in those views you need to declare it with@ObservedObject
– Adelbert@StateObject
does not change a thing. Essentially, ObservableObjects with Published properties are not allowed to be reference bound since iOS16 and Swift 4. You need to use an@State
property without ever touching it manually ever again. – ParoleeObservableObject
withPublished
is no longer correct? So what is the use ofPublished
now? – Crumley