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

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.

3      

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

4      

Thank you so much, works perfectly!

3      

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.