Updated for Xcode 13.3
SwiftUI gives us a dedicated shadow()
modifier to draw shadows around views. You can control the color, radius, and position of the shadow, and you can also control which parts of the view get shadowed by adjusting your modifier order.
In its basic form, you can add a shadow just by specifying the radius of the blur, like this:
Text("Hacking with Swift")
Download this as an Xcode project
.foregroundColor(.black)
.padding()
.shadow(radius: 5)
.border(.red, width: 4)
.background(.white)
That adds a very slight shadow with a 5-point blur centered on the text.
You can also specify which color you want along with the X and Y offset from the original view. For example, this creates a strong red shadow with a 5-point blur, centered on the text:
Text("Hacking with Swift")
Download this as an Xcode project
.padding()
.shadow(color: .red, radius: 5)
.border(.red, width: 4)
If you want to specify offsets for the shadow, add x
and/or y
parameters to the modifier, like this:
Text("Hacking with Swift")
Download this as an Xcode project
.padding()
.shadow(color: .red, radius: 5, x: 20, y: 20)
.border(.red, width: 4)
Remember, SwiftUI applies modifiers in the order you list them, so if you want you can have your shadow apply to the border as well just by putting the border modifier before the shadow modifier:
Text("Hacking with Swift")
Download this as an Xcode project
.padding()
.border(.red, width: 4)
.shadow(color: .red, radius: 5, x: 20, y: 20)
Tip: If you find your shadow effect isn’t strong enough, add another shadow()
modifier – you can stack them up to create more complex shadow effects.
SPONSORED Fernando's book will guide you in fixing bugs in three real, open-source, downloadable apps from the App Store. Learn applied programming fundamentals by refactoring real code from published apps. Hacking with Swift readers get a $10 discount!
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.