SWIFTUI. How to permanently change the color of the buttons after clicking?

Viewed 595

I am building a quiz app. A question; 3 answers. The answers are in separate buttons.

I managed the change the color of the buttons when clicked. Eg from gray to green/red. But after the click the button goes back to gray.

Is there a way to keep the changed colors after the click, like a hyperlink in HTML?

This is the style code:

struct MyButtonStyle: ButtonStyle {

  func makeBody(configuration: Self.Configuration) -> some View {
    configuration.label
      .padding(20)
      .foregroundColor(.white)
      .background(configuration.isPressed ? Color.red : Color.gray)
      .cornerRadius(10.0)
2 Answers

You can declare your ButtonStyle like this:

public struct SelectedButtonStyle: ButtonStyle {

    @Binding var isSelected: Bool

    public func makeBody(configuration: Self.Configuration) -> some View {
        configuration.label
            .padding(20)
            .foregroundColor(.white)
            .background(isSelected ? Color.red : Color.gray)
            .cornerRadius(10.0)
    }
}

and then in the view, have a state for the selction:

@State var isSelected = false

and then you can either declare your button like this to have it selected once and forever stay selected:

Button("Tap") {
    self.isSelected = true
}   .buttonStyle(SelectedButtonStyle(isSelected: $isSelected))

or you can declare it like this to be able to deselect it as well:

Button("Tap") {
    self.isSelected.toggle()
}   .buttonStyle(SelectedButtonStyle(isSelected: $isSelected))

try something like this, once isPressed becomes true it won't become false again, so the button will stay gray

struct ContentView: View {

   @State private var isPressed = false

    var body: some View {
        Button(action: {
            self.isPressed = true
        }, label: {
            Text("Button").accentColor(isPressed ? Color.gray : Color.blue)
        })
    }
}
Related