This simple example demonstrates that the .onChange statement does not execute on the first selection, but does print the selection upon the second and later selections.
Looking for an explanation and a fix if one exists.
import SwiftUI
// Xcode version 13.4.1 (13F100)
let myFruits: [String] = ["Apple","Banana","Grape","Peach"]
struct ContentView: View {
@State var fruitName: String = "none"
var body: some View {
VStack {
Menu {
PickFruit(fruitName: $fruitName)
} label: {Text("Select A Fruit")}
Text(fruitName)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
struct PickFruit: View {
@Binding var fruitName: String
var body: some View {
VStack {
Text(fruitName)
Picker("Select", selection: $fruitName) {
ForEach(myFruits, id: \.self) { myFruits in
Text(myFruits)
}
}.onChange(of: fruitName) {newValue in print(newValue)}
}
}
}
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
New guy here, hacking away on the SwiftUI tutorial (https://developer.apple.com/tutorials/swiftui/building-lists-and-navigation ):
In MapView.swift it would be useful to add a pin/marker. Thus adding:
struct Place: Identifiable {
let id = UUID()
let name: String
let coordinate: CLLocationCoordinate2D
}
var annotations = [
Place(name: "Xyz", coordinate: CLLocationCoordinate2D(latitude: 34.011286, longitude: -116.166868))
]
and modifying the View to:
var body: some View {
Map(coordinateRegion: $region, annotationItems: annotations) {
MapPin(coordinate: $0.coordinate)
}
.onAppear {
setRegion(coordinate)
}
}
puts a pin on the Turtle Rock map using the hard-coded latitude and longitude.
However, changing (latitude: 34.011286, longitude: -116.166868) to (latitude: coordinate.latitude, longitude: coordinate.longitude) results in error "Cannot use instance member 'coordinate' within property initializer; property initializers run before 'self' is available."
What modifications to the project are required to access the latitude and longitude for use in the annotation?