Is there a way for a button background color to remain changed after being selected?

Viewed 86

The following code changes the button background color when pressed, but goes back to original background when when released. I would like the button to remain selected.

struct MyButtonStyle: ButtonStyle {

func makeBody(configuration: Configuration) -> some View {
    configuration.label
      .padding()
      .foregroundColor(configuration.isPressed ? Color.white : Color("greenColor"))
      .background(configuration.isPressed ? Color.red : Color.clear)
  }

}

2 Answers

Here's a possible solution, not using a custom button. Just keeping track of a State variable if button is tapped do something. The first button uses a plain style with cornerRadius, the second button use the borderedProminent style but this shows with a highlight on button tap.

button

struct ContentView: View {
    @State var firstbutton: Bool = false
    @State var secondbutton: Bool = false
    // AppStorage saves state when app is killed
    //@AppStorange("tapped") var tapped: Bool = false
    var body: some View {
        Button(action: {
            firstbutton.toggle()
            /*
             if once
             toggle = true
             */
        }, label: {
            Label("Button", systemImage: "square.and.arrow.up")
                .foregroundColor(firstbutton ? Color.white : Color.green)
                .padding(.all, 10)
        })
        .background(firstbutton ? Color.red : Color.clear)
        .cornerRadius(5)
        .buttonStyle(.plain)
        
        
        Button(action: {
            secondbutton.toggle()
            /*
             if once
             toggle = true
             */
        }, label: {
            Label("Button", systemImage: "square.and.arrow.up")
                .foregroundColor(secondbutton ? Color.white : Color.green)
                .padding(.all, 10)
        })
        .tint(secondbutton ? Color.red : Color.clear)
        .buttonStyle(.borderedProminent)
    }
}

We can do that by introducing state in button style and make style changes dependent on it, while updating state conditionally when needed.

demo

Here is main part of approach (tested with Xcode 13.3 / iOS 15.4)

    .background(flag ? Color.red : Color.clear)
    .onChange(of: configuration.isPressed) {
        if $0 {
            flag.toggle()
        }
    }

Completed report and code is here

Related