Shadow modifier adds a shadow to the view. Shadow modifier takes four parameters.
Color
: defines the color for Shadow
Radius
: sets the size of Shadow.
x
: this is a horizontal offset we use to position shadow relative to the view its being applied.
y
: this is a vertical offset we use to position shadow relative to the view its being applied.
Only parameter required by Shadow
modifier is radius
. Let’s look at it with an example.
struct DevTechieShadowExample: View {
var body: some View {
VStack {
Text("DevTechie")
.font(.largeTitle)
.frame(width: 200, height: 200)
.background(.white)
.shadow(radius: 2)
}
}
}
We can change shadow color using color parameter.
.shadow(color: .orange, radius: 2)
We can offset shadow on x axis using x parameter
.shadow(color: .orange, radius: 2, x: 20)
and set y offset using y parameter.
.shadow(color: .orange, radius: 2, x: 20, y: 20)
Notice that shadow is applied to child views as well. For example, in this case both box and text DevTechie has shadow. What if we want to apply shadow only to the outer box but not to the child views? We can solve this couple of ways.
One way is to apply shadow to the background.
struct DevTechieShadowExample: View {
var body: some View {
VStack {
Text("DevTechie")
.font(.largeTitle)
.frame(width: 200, height: 200)
.background(Color.white.shadow(color: .orange, radius: 2, x: 20, y: 20))
}
}
}
Or we can add clipped
modifier to achieve the same results.
struct DevTechieShadowExample: View {
var body: some View {
VStack {
Text("DevTechie")
.font(.largeTitle)
.frame(width: 200, height: 200)
.background(.white)
.clipped()
.shadow(color: .orange, radius: 2, x: 20, y: 20)
}
}
}