I have a ForEach loop that displays ten unfilled buttons. When the button is clicked, the button assigns the index of the clicked button to a @State variable; only when the value of the state variable is equal to the index of the clicked button is the button filled. What should I change to be able to 1) click on the same button to unfill the button, and 2) fill another button without "unfilling" any already filled buttons?
Here is a minimal, reproducible example:
import SwiftUI
struct Test: View {
@State var selection: Int? = nil
var body: some View {
VStack {
ForEach (0 ..< 10, id: .self) { number in
Button (action: {
self.selection = number
}, label: {
self.selection == number ? Image(systemName: "heart.fill") : Image(systemName: "heart")
})
}
}
}
}
struct Test_Previews: PreviewProvider {
static var previews: some View {
Test()
}
}
Thanks in advance.
2
Answers
You have to maintain state separately for each button.Better option is to use array. Check code below.
You need to have a selection property that can keep track of multiple buttons, not just one button. I would use a
Set
here (not anArray
, because there’s no handyremove
-object method there)