With SwiftUI, you can easily create a button with a gradient background. Not only can you define a specific background modifier color, but you can also apply a gradient effect to any button.
All you need to do is replace this line of code:
.background(.blue)
with this:
.background(LinearGradient(gradient: Gradient(colors: [.red, .blue]), startPoint: .leading, endPoint: .trailing)
The SwiftUI framework comes with many built-in gradient modifiers. The above code applies a linear gradient from the left (.leading) to the right (.trailing). It starts with red on the left and ends with blue on the right.
This would be the result:
How to add a shadow to a button
To add a shadow to a button we use the shadow modifier which allows us to draw a shadow around the button (or any view). Just add this line of code to add a shadow:
.shadow(radius: 5.0)
In our example the code would look like this:
import SwiftUI
struct ContentView: View {
var body: some View {
Button {
print("Delete button tapped")
} label: {
Label(
title: {
Text("Macbook")
.fontWeight(.semibold)
.font(.title)
},
icon: {
Image(systemName: "macbook")
.font(.title)
}
)
.padding()
.foregroundStyle(.white)
.background(LinearGradient(gradient: Gradient(colors: [.red, .blue]), startPoint: .leading, endPoint: .trailing))
.cornerRadius(40)
.shadow(radius: 5.0)
}
}
}
Optionally, you can control the color, radius, and position of the shadow. Here’s an example:
.shadow(color: .gray, radius: 20.0, x: 20, y: 10)