From the tutorial https://developer.apple.com/tutorials/swiftui/handling-user-input, it has the star to indicate "isFavourite".
I have changed the star to a button, if the user tapped on it, and then it will toggle the isFavourite value.
struct LandmarkRow: View {
@State var landmark: Landmark
@State var isChecked: Bool = false
var body: some View {
HStack {
landmark.image
.resizable()
.frame(width: 50, height: 50)
Text(landmark.name)
Spacer()
Button(action: {
self.isChecked.toggle()
landmark.isFavourite.toggle() // tried to modify the landmark value
}, label: {
if self.isChecked {
Image(systemName: "checkmark.square.fill")
.imageScale(.large)
} else {
Image(systemName: "square")
.imageScale(.large)
}
})
}
}
}
However, I found an issue here.
Back to the LandmarkList view, I would like to count how many are landmarks are selected. However, when I use a for loop to loop through the landmarks, I found that the isFavourite value is not modified.
struct LandmarkList: View {
var body: some View {
NavigationView {
VStack {
Text("\(getCount(landmarks)") // fail here, it shows 0 forever
List(landmarks) { landmark in
NavigationLink(destination: LandmarkDetail(landmark: landmark)) {
LandmarkRow(landmark: landmark)
}
}
}
.navigationTitle("Landmarks")
}
}
}
I have a function getCount in the LandmarkList:
func getCount(landmarks: [Landmark]) -> Int {
var count: Int = 0
for landmark in landmarks {
if landmark.isFavourite {
count += 1
}
}
return count
}
Is that because of the @State? Or what have been wrong here?