Button actions from ForEach generated buttons

Please help. How do I get each button to perform a different action? With my code below every button does the same action when pressed.


var num:[String] = ["one", "two", "three", "four"]
struct test: View {
    var body: some View {
        VStack{
        ForEach(num, id: \.self)
        {index in
           
        Button(index) {
            print("Button pressed")
        }
        .padding()
        .clipShape(Capsule())
          .foregroundColor(Color.black)
          .background(Color.green.opacity(0.2))
          .font(.caption)
          .cornerRadius(13.0)
     }
    }
}
}
struct test_Previews: PreviewProvider {
    static var previews: some View {
        test()
    }
}

Any thoughts? Todd

Every button performs the same action because you are using the same code for every button. If you want them to do something different, you need to give them different action closures.

Generating your buttons through a ForEach isn’t a good idea if you want them all to have different actions, unless those actions are just variations on a single action. Like, if you wanted to print the button’s title or index or something like that but everything else about each button should be the same, then a ForEach would be a good way to generate them.

What are you expecting each button in your example code to do?

Hi @toddrmyers11

I think you need to pass or get the index you’re currently with. See the explanation below.

As you can see, I moved your array variable inside your struct, line no. 12.

Starting from line 17, you created a ForEach loop and assigned the temporary value to a constant named index and used that to name your button. :slight_smile:

I just added the index value on line 19 for you to get one index value at a time. Then I closed the loop in line 20.

I’m not sure if I explain it clearly but I hope you understand.

:point_up_2:t2:
@toddrmyers11
This is a much clear explanation on what I’m trying to explain. :smile:

Thank you, @roosterboy!

Thanks for the reply. I just want to add the name of the button to a text field. I want to build a paragraph based on the buttons that the user selects. There are many buttons that I might want to change over time so I put them in an array in the json file. I’m not sure if this is the best way to do it. I’m not sure how to assign the name of the button to variable in another view file.

Todd

Thanks for the help

Hi Todd, you’d have to pass the variable from one view to another by either binding or using a StateObject