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      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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.