Hey guys, I was just learning the SwiftUI Tutorials, and I was quite confused about the Map preview in the following code:
import SwiftUI
import MapKit
struct MapView: View {
var coordinate: CLLocationCoordinate2D
@State private var region = MKCoordinateRegion()
func setRegion(_ coordinate: CLLocationCoordinate2D) {
region = MKCoordinateRegion(
center: coordinate,
span: MKCoordinateSpan(latitudeDelta: 0.2, longitudeDelta: 0.2)
)
}
var body: some View {
Map(coordinateRegion: $region)
.onAppear {
setRegion(coordinate)
}
}
}
struct MapView_Previews: PreviewProvider {
static var previews: some View {
MapView(coordinate: CLLocationCoordinate2D(latitude: 34.011_286, longitude: -116.166868))
}
}
As you see, the preview shows a map of blue sea, instead of what I would like to see (the location of Joshua Tree).
However, when I use MapView() in another view structure by embedding it within a HStack (VStack, ScrollView works as well ), the preview shows perfectly what I want:
import MapKit
struct MapViewDemo: View {
var body: some View {
HStack {
MapView(coordinate: CLLocationCoordinate2D(latitude: 34.011_286, longitude: -116.166868))
}
}
}
struct MapViewDemo_Previews: PreviewProvider {
static var previews: some View {
MapViewDemo()
}
}
Could you help me understand why it works this way? Is it the particular way how Map or .onAppear works?