I will demonstrate on how to create a customised button in SwiftUI.
Firstly I will create a MaterialColor enum that will define different color sets so that I can create button with different color easily.
Then I create the customized ButtonStyle:
that will:
- set minHeight to 44.0
- add a padding in leading and trailing
- add a background that fill a round rectangle. Although a round corner can be done by cornerRadius modifier, it will clip the view and so cannot add shadow to button. That’s why I draw the background with round rectangle, and add a shadow on it that will vary by the isPressed status.
- add another circle shape background that add button press animation
- add an overlay to draw the stroke of the round rectangle
To use the button, simply add the button style to the button:
Button("Primary") {}.buttonStyle(MaterialButtonStyle())
or use different color:
Button("Danger") {}.buttonStyle(MaterialButtonStyle(color: .danger))
If you want to have the button expanded to the parent view’s width, you can set the maxWidth:
Button("Border Danger") {}.buttonStyle(MaterialButtonStyle(color: .danger, maxWidth: true))
Unlike the original material design button, that the ripple effect starts from the button click location, this implementation starts from the center of the button. It is because unlike UIView, I cannot get the button click location in SwiftUI.
Source Code
The full source code can be downloaded here:
https://github.com/waterloucodesamples/MediumMaterialDesignButton