NEW: Start my new Ultimate Portfolio App course with a free Hacking with Swift+ trial! >>

SOLVED:button background colours

Forums > SwiftUI

I know this must seem basic but I can't get it to work. I want a button to change color when tapped but start grey, turn green on first tap then red on second tap and back to grey on third. I thought .background(Color.array[number]) in a foreach loop would do it but apparently not. Eventually I want to store the state of the button, so I don't think toggle would work.

   

Firstly it a very good question, so do not be worried about asking thing on this forum.

I have done this which works but not sure if it what you are looking for:

Make a struct (I usually put it in a file)

struct ChangeColorButton: ButtonStyle {
    let colors: [Color] = [.gray, .green, .red]
    let number: Int

    func makeBody(configuration: Configuration) -> some View {
        configuration.label
            .padding()
            .background(colors[number])
    }
}

then where you want to to place the button

struct ContentView: View {
    @AppStorage("buttonstatus") var number: Int = 0 // This store the color of button

    var body: some View {
        Button("Change Color") {
            changeColor()
        }
        .buttonStyle(ChangeColorButton(number: number))
    }

    func changeColor() {
        if number == 2 {
            number = 0
        } else {
            number += 1
        }
    }
}

   

Thank you so much, works perfectly!

   

Hacking with Swift is sponsored by RevenueCat

SPONSORED Building and maintaining in-app subscription infrastructure is hard. Luckily there's a better way. With RevenueCat, you can implement subscriptions for your app in hours, not months, so you can get back to building your app.

Try it for free

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.