SwiftUI buttons and gradient

There are lots of tools in SwiftUI to make your buttons look any way you want them to and this chapter leads you through the process of button creation and enhancement. It also shows how to create a ButtonStyle that works very similarly to a CSS rule in an html document. Instead lines and lines of coding for each of multiple buttons, you can create one ButtonStyle instead.

I wasn’t super impressed with how they outline the process of creating a ButtonStyle and at least one portion of the instructions is out of date. They mention building your ButtonStyle above #if DEBUG:  which no longer appears in SwiftUI files.  Just place the ButtonStyle code that they provide above or below the preview struct instead.

But I want to take the ButtonStyle thing just a bit further. The author shows you how to style the text of a button with fonts,  how to add a frame that sets the width,  how to set the foreground and background colors, linear gradient, padding, and cornerRadius. All of those elements can become part of a ButtonStyle except the font portion. So, if you have a lot of formatting that you want to use to create a ButtonStyle such as the formatting show below, for example, you would need to copy everything except the font portion and paste it into your new ButtonStyle.

.fontWeight(.bold)
.font(.title)
.frame(minWidth: 0, maxWidth: .infinity)
.padding()
.background(LinearGradient(gradient: Gradient(colors: [Color.red, Color.blue]), startPoint: .leading, endPoint: .trailing))
.shadow(color: .gray, radius: 20.0, x: 20, y: 10)
.foregroundColor(.white)
.cornerRadius(30)
.padding(.horizontal, 20)

For example, I have created a new ButtonStyle from the same formatting and below you can see how it turned out.

struct MyButtonStyle: ButtonStyle {
func makeBody(configuration: Self.Configuration) -> some View {
configuration.label
.frame(minWidth: 0, maxWidth: .infinity)
.padding()
.foregroundColor(.white)
.background(LinearGradient(gradient: Gradient(colors: [Color("DarkGreen"), Color("LightGreen")]), startPoint: .leading, endPoint: .trailing))
.cornerRadius(40)
.padding(.horizontal, 20)
}
}

If you ever want to create your very own ButtonStyle, simple copy the following code and past YOUR formatting on the line just after configuration.label

struct MyButtonStyle: ButtonStyle {
func makeBody(configuration: Self.Configuration) -> some View {
configuration.label

}
}

I hope you enjoy this lesson. If you ever go into this line of work, I’m certain that ButtonStyles will become part of your professional toolkit.