UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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!

2      

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

4      

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

2      

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

2      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.