Buttons are one of the essential components of a mobile app and styling them gives your app its own identity. Luckily for us, SwiftUI has several styling protocols that allow users to define styling for views such as Button, Toggle and more. SwiftUI enables us to create custom buttons through a modifier, that way the style is reusable.
For this tutorial, let’s do a quick dive into how to create those reusable button styles in a way that avoids repeating code across your app.
Let’s say we have a button like this:
Button("Send Gift 🎁", action: doSomething)
.font(.title)
.foregroundColor(Color.red)
.padding(EdgeInsets(top: 8, leading: 16, bottom: 8, trailing: 16))
.background(Color.green)
.clipShape(RoundedRectangle(cornerRadius: 8))
Converting this into a reusable button style is as easy as conforming to the ButtonStyle protocol
struct GiftButtonStyle: ButtonStyle {
func makeBody(configuration: Configuration) -> some View { //... }
}
and attaching your modifiers to the configuration.label
struct GiftButtonStyle: ButtonStyle {
func makeBody(configuration: Configuration) -> some View {
configuration.label
.font(.title)
.foregroundColor(Color.red)
.padding(EdgeInsets(top: 8, leading: 16, bottom: 8, trailing: 16))
.background(Color.green)
.clipShape(RoundedRectangle(cornerRadius: 8))
}
}
From there, we can now simplify our code and also reuse the same style just as easily!
Button("Send Gift 🎁", action: doSomething).buttonStyle(GiftButtonStyle())
Button("Open Gift 🎁", action: doSomething).buttonStyle(GiftButtonStyle())
That’s it! Enjoy your designer buttons!
More from
Engineering
Importance of Design QA workflow
Marvin Fernandez, Engineering Manager
SQA questions to ponder
Joy Mesina, QA
Writing a Software Test Plan
Ron Labra, Software Quality Analyst