I want to custom some button styles. But after applying them, the .controlSize() modifier will stop working, as shown in below screenshot. Is it possible to support .controlSize() in custom ButtonStyle or some approaches else can bring this control size back?
struct ContentView: View {
var body: some View {
VStack {
Button("Hello World") { }
.buttonStyle(.borderedProminent)
.controlSize(.regular)
Button("Hello World") { }
.buttonStyle(CustomButtonStyle())
.controlSize(.regular)
}
.padding()
}
}
struct CustomButtonStyle: ButtonStyle {
func makeBody(configuration: Configuration) -> some View {
configuration.label
.background(Color.cyan)
.border(Color.brown)
}
}
>Solution :
Yes it is.
You can check the controlSize environment value in your custom style and adjust accordingly. For example:
struct CustomButtonStyle: ButtonStyle {
@Environment(\.controlSize) var controlSize
// Ideally switch over every value and produce different styles
func makeBody(configuration: Configuration) -> some View {
configuration.label
.font(controlSize == .large ? .title : .body)
.background(Color.cyan)
.border(Color.brown)
}
}
