Home > Mobile >  I can't seem to be able to update the state of my index variable(SwiftUI)
I can't seem to be able to update the state of my index variable(SwiftUI)

Time:06-13

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")
               }
            }
        }
    }
}

CodePudding user response:

This should work just like what you wanted. I made a Test view, you can follow the same logic.

import SwiftUI

struct Test: View {

@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]

var body: some View {
    
    ForEach(0..<buttons.count, id: \.self) { index in
               Button(action: {
                  print(index)
               }) {
                   Label(buttons[index], systemImage: "paintbrush.pointed")
                  }
    }
}
}

CodePudding user response:

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.

struct Idontcare: View { //Has to conform to View
    @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]

        var body: some View { //was missing in your Code
            showMenu()
        }




    func showMenu() -> some View{
        return Menu("Update Color: "){
            ForEach(buttons, id: \.self) { button in
                Button(action: {
                    self.index = 5 //Works now
                    print(self.index)
                }) {
                    Label(button, systemImage: "paintbrush.pointed")
                }
            }
        }
    }
}
  • Related