NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

SOLVED: Change background for Buttons in ForLoop.

Forums > SwiftUI

I feel like this is simple, but I've spent too much time trying to work it out.

I have a ForEach loop creating 4 Buttons. All of these buttons have a default background. When a button gets tapped, the button turns green using a ternary op. Now, if the user changes their mind and selects another button from this loop, I'd like for the user's first option to retrun to its default color, and for this new option to turn green.

Here's a sample code:

struct QuestionButtons: View {
    @State var isSelected       = [false, false, false, false]
    var numberArray = [5,10,15,20]
    var body: some View {
        HStack(spacing: 20){
            ForEach(0..<numberArray.count){n in

                Button("\(numberArray[n])"){

                    isSelected[n]   = true

                }
                .frame(width: 60, height: 60)
                .background(isSelected[n] ? .green : .teal)
                .foregroundColor(.black)
                .cornerRadius(10)
                .shadow(radius: 5)
            }
        }
    }
}

Thanks to whoever can help me proceed with this project!

   

How about something like this?:

struct QuestionButtons: View {
    @State private var selection: Int?
    var numbers = [5,10,15,20]
    var body: some View {
        HStack(spacing: 20){
            ForEach(numbers){ number in
                Button("\(number)"){
                if selection == number {
                  selection = nil // deselect if pressed while active
                } else {
                    selection = number // make active if pressed when not active
                }
                .frame(width: 60, height: 60)
                .background(selection == number ? .green : .teal)
                .foregroundColor(.black)
                .cornerRadius(10)
                .shadow(radius: 5)
            }
        }
    }
}

2      

@TravelByRocket Yes! Thank you. Hate that I couldn't figure it out, but love that I can count on awesome people like you!

   

The slog is real! I've been stuck on the same problem before and many more will after you :-)

   

Hacking with Swift is sponsored by Play

SPONSORED Play is the first native iOS design tool created for designers and engineers. You can install Play for iOS and iPad today and sign up to check out the Beta of our macOS app with SwiftUI code export. We're also hiring engineers!

Click to learn more about Play!

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.