I'm trying to create a custom button style that encapsulates default background, colors, and font that can be used in a few different contexts by slightly tweaking the layout.
For example, I can add a color background and some default padding:
struct ExampleButtonStyle: ButtonStyle {
func makeBody(configuration: Configuration) -> some View {
configuration.label
.padding(EdgeInsets(top: 10, leading: 16, bottom: 10, trailing: 16))
.background(Color.red)
}
}
However, if I want to reuse this button style's background, font, and coloring but just change the layout to be the full width of the screen, things don't work as expected.
Button("Hello world") { }
.buttonStyle(ExampleButtonStyle())
.frame(maxWidth: .infinity)
In this case, the Button does stretch to fill the view it's in, but the red colored background stays the same content size + padding. Is there a different way to get the expected behavior, that the styled layout size can be tweaked with additional view modifiers? Or are we just expected to create different ButtonStyles or pass a configuration parameter into the ButtonStyle initializer?