Quit using Button(action: {}, label: {})
Turn this
Button(action: {
//action
}, label: {
Text("Done")
})
Into this
Text("Done")
.button {
//action
}
I hate how messy the default `Button` syntax can get. The first thing I do when starting a new project is make the below custom ViewModifier to clean up the code and make things easier to read. I've done it so much I thought it was time to share, hopefully y'all find it useful. Take care.
struct ButtonModifier<S: PrimitiveButtonStyle>: ViewModifier {
let buttonstyle: S
var onTap: () -> ()
func body(content: Content) -> some View {
Button(action: {
self.onTap()
}, label: {
content
})
.buttonStyle(buttonstyle)
}
}
extension View {
func button<S: PrimitiveButtonStyle>(buttonstyle: S = .automatic, onTap: @escaping () -> ()) -> some View {
self.modifier(ButtonModifier(buttonstyle: buttonstyle, onTap: onTap))
}
}
Posted Oct 10, 2025, 7:15 PM UTC
010