I want depending on which button is pressed to update the index number. Also when I print it, I want it to show me that it is well updated.
struct idontcare { //Named it this way cause I got mad
@State var index: Int = 0
let buttons: [String] = [ "Primary", "Blue", "Green", "Red", "Yellow", "Orange","Gray", "Purple", "Cyan", "Pink", "Teal"]
let buttonColor: [Color] = [Color.primary, Color.blue, Color.green, Color.red, Color.yellow, Color.orange, Color.gray, Color.purple, Color.cyan, Color.pink, Color.teal]
func showMenu() -> some View{
return Menu("Update Color: "){
ForEach(buttons, id: .self) { button in
Button(action: {
self.index = 5 //DOES NOT WORK!!
print(self.index) //ALWAYS PRINTS 0!
}) {
Label(button, systemImage: "paintbrush.pointed")
}
}
}
}
}
3
Answers
You code is missing the
body property
.The struct "Idontcare" has to conform to
View
, it might got lost while pasting to your question.However, if I add both to your code, everything works fine for me.
This should work just like what you wanted. I made a Test view, you can follow the same logic.
You can try the below code. it will help you to get selected button index.