SALE ENDS TODAY: Save 50% on all Swift books and bundles! >>

How to draw a shadow around a view

Paul Hudson    @twostraws   

Fully updated for Xcode 11.2

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")
    .padding()
    .shadow(radius: 5)
    .border(Color.red, width: 4)

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")
    .padding()
    .shadow(color: .red, radius: 5)
    .border(Color.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")
    .padding()
    .shadow(color: .red, radius: 5, x: 20, y: 20)
    .border(Color.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")
    .padding()
    .border(Color.red, width: 4)
    .shadow(color: .red, radius: 5, x: 20, y: 20)

SPONSORED Instabug helps you identify and resolve severe crashes quickly. You can retrace in-app events and know exactly which line of code caused the crash along with environment details, network logs, repro steps, and the session profiler. Ask more questions or keep users up-to-date with in-app replies straight from your dashboard. Instabug takes data privacy seriously, so no one sees your data but you! See more detailed features comparison and try Instabug's crash reporting SDK for free.

Save 50% on all books and bundles

The biggest ever Hacking with Swift sale is now on, letting you save 50% on all books and bundles. Learn something new with Swift and enjoy great savings while the sale lasts!

Click here to save 50% in our Black Friday sale!

Similar solutions…

BUY OUR BOOKS
Buy Pro Swift Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift (Vapor Edition) Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.7/5