Add Shadows to Views in SwiftUI
Written by Team Kodeco
Have you ever wondered how to make your views pop out of the screen? Adding shadows can give your views a sense of depth and make them stand out. SwiftUI provides easy ways to add shadows to your views by using modifiers.
To add a shadow to a view, you can use the shadow modifier. Let’s take a look at an example:
struct ContentView: View {
var body: some View {
Text("Hello, Shadows!")
.font(.largeTitle)
.padding()
.background(Color.white)
.shadow(radius: 10)
}
}
The preview for this view should look as follows:
In this example, you’ve added a shadow to a text view. First, you set the font size to thelargeTitle style and added padding to create some space around the text. Then you added a white background to the text view using the background modifier. Finally, you added a shadow to the text view by chaining the shadow modifier and specifying the radius of the shadow.
The shadow modifier takes a few parameters that you can use to customize the shadow. The radius parameter specifies the blur radius of the shadow, while the x and y parameters specify the offset of the shadow in the horizontal and vertical directions respectively.
Colored Shadows
You can also control the shadow color. Try this out by adding a simple shadow to a shape:
struct ContentView: View {
var body: some View {
VStack {
Text("Hello, Shadows!")
.font(.largeTitle)
.padding()
.background(Color.white)
.shadow(radius: 10)
Circle()
.fill(Color.blue)
.shadow(color: .purple, radius: 10, x: 0, y: 0)
.padding(EdgeInsets(top: 10, leading: 10, bottom: 10, trailing: 10))
}
}
}
The preview for this view should look as follows:
In this example, we’ve created a blue circle and added a purple shadow to it. You specified the radius of the shadow to be 10, and the offset to be 0 points in both the horizontal and vertical directions (so the shadow is centered).
Adding a shadow effect to a view is a simple way to enhance the overall design of your interface without overloading it with details. Start experimenting with the shadow modifier in SwiftUI and see how it can bring your user interface to life!