Custom button not respecting the size defined in frame

Hi everyone,

I created a custom ButtonStyle.

struct ContentView: View {
    var body: some View {
        VStack {
            Button("Get Started") {
                print("button tapped")
            }
            .buttonStyle(PrimaryButtonStyle())
            .frame(width: 320, height: 50)
            .border(.red, width: 1)
        }
        .padding()
    }
}

public struct PrimaryButtonStyle: ButtonStyle {
    @Environment(\.isEnabled) var isEnabled
    
    public func makeBody(configuration: Configuration) -> some View {
        configuration.label
            .fontWeight(.medium)
            .background(.green)
            .foregroundStyle(.white)
            .clipShape(RoundedRectangle(cornerRadius: 6))
            .opacity(configuration.isPressed ? 0.8 : 1)
            .saturation(isEnabled ? 1 : 0)
    }
}

I used hat style on a button and also set a size using frame. But the background is not filling up to the size.

You can see the frame is there (I added the red border to debug it) but the background is not filling it. I switched the positions of the modifiers on the button but that has no effect either.

What am I missing here? Any help is appreciated. Thank uoi.

Answered by jlilest in 775086022

You are setting the background for the label and not the button as a whole.

Accepted Answer

You are setting the background for the label and not the button as a whole.

Custom button not respecting the size defined in frame
 
 
Q