If else statement on ForegroundColor SwiftUI

Viewed 926

I wanted to do a simple if-else statement on a button

Button(action: {self.theSoal = nomor.id}) {
            Circle()
                .frame(width:80,height: 80, alignment:.center)
                .foregroundColor(.blue)
                .overlay(
                    Text("99")
                        .font(.title)
                        .fontWeight(.bold)
                        .foregroundColor(.white)
                    
                )
        }

see that .blue, so I wanted to a conditional statement of if the button is clicked then the color change from .blue to .yellow

how do I do it?? well so far my options are using a state?

state color = "blue"

if the button is pushed then color = "yellow"

shortish, but it's not good and I need to add the color to my self

so is there a way to deal with it??

This is how the button looks like enter image description here

1 Answers

Persist Color

If you want to change the color and you want it to continue with that color,

  1. First you need to define a State for the button

  2. Then you need to toggle the state inside the button's action

  3. And lastly, You make the color of the button conditional

struct ContentView: View {

    @State var isActive = false // <- Check this out

    var body: some View {

        Button {
            theSoal = nomor.id
            isActive.toggle() // <- Check this out
        } label: {
            Circle()
                .frame(width: 80, height: 80, alignment:.center)
                .foregroundColor(isActive ? .blue : .yellow) // <- Check this out
                .overlay(
                    Text("99")
                        .font(.title)
                        .fontWeight(.bold)
                        .foregroundColor(.white)
                )
        }
    }
}

Preview 1


Touch down color

If you want it to change color on touch-down and revert the color on touch-up then you need to define a custom style:

struct CustomButton: ButtonStyle {
    func makeBody(configuration: Configuration) -> some View {
        configuration.label
            .frame(width: 80, height: 80, alignment:.center)
            .font(Font.title.weight(.bold))
            .foregroundColor(.white)
            .background(configuration.isPressed ? Color.yellow : .blue) // <- Check this out
            .clipShape(Circle())
    }
}

And the usage code would be like:

struct ContentView: View {

    var body: some View {
        Button("99") { theSoal = nomor.id }
        .buttonStyle(CustomButton())
    }
}

Note that you can encapsulate your configuration inside the style

Preview 2

Related