How to remove highlight on tap of Button with SwiftUI?

Viewed 1081

I have a button and label for this simple app. When I tap the button, it highlights my button (you can see in the attached image), so how can I disable that? What am I missing?

Code:

struct ContentView: View {
    @State private var displayLabel = 0
    var body: some View {
        GeometryReader{ geo in
            ZStack{
                Button(action: {
                    displayLabel += 1
                }, label: {
                    Rectangle()
                        .foregroundColor(.blue)
                        .frame(width: geo.size.width, height: geo.size.height)
                }).buttonStyle(PlainButtonStyle())
                
                Text("\(displayLabel)")
                    .font(Font.system(size:75, design: .rounded))
            }
        }
    }
}

enter image description here

2 Answers

You can create a custom ButtonStyle with no highlighting:

struct StaticButtonStyle: ButtonStyle {
    func makeBody(configuration: Configuration) -> some View {
        configuration.label
    }
}
Button(action: {
    displayLabel += 1
}) {
    Rectangle()
        .foregroundColor(.blue)
        .frame(width: geo.size.width, height: geo.size.height)
}
.buttonStyle(StaticButtonStyle())

Apply the style .plain to your button to avoid overlay color.

// Before
Button(...) 

with button styling

// After
Button(...)
.buttonStyle(.plain) // Remove the overlay color (blue) for images inside Button 
  • .plain button style, that doesn’t style or decorate its content while idle, but may apply a visual effect to indicate the pressed, focused, or enabled state of the button.

without button styling

Another solution is to custom the style with ButtonStyle

like: struct MyButtonStyle:ButtonStyle { }

Related