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 Fernando Olivares

SPONSORED Would you describe yourself as knowledgeable, but struggling when you have to come up with your own code? Fernando Olivares has a new book containing iOS rules you can immediately apply to your coding habits to see dramatic improvements, while also teaching applied programming fundamentals seen in refactored code from published apps.

Try the book!

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.