NEW: Get your ticket for Hacking with Swift Live 2019! >>

How to add a shadow to a UIView

Swift version: 5.0

Paul Hudson    @twostraws   

iOS can dynamically generate shadows for any UIView, and these shadows automatically adjust to fit the shape of the item in question – even following the curves of text inside a UILabel. This functionality is built right in, so all you need to do is configure its properties, and there are four you need to care about:

  • shadowColor sets the color of the shadow, and needs to be a CGColor.
  • shadowOpacity sets how transparent the shadow is, where 0 is invisible and 1 is as strong as possible.
  • shadowOffset sets how far away from the view the shadow should be, to give a 3D offset effect.
  • shadowRadius sets how wide the shadow should be.

Here's a simple example to get you started:

let yourView = UIView()
yourView.layer.shadowColor = UIColor.black.cgColor
yourView.layer.shadowOpacity = 1
yourView.layer.shadowOffset = .zero
yourView.layer.shadowRadius = 10

Be warned: generating shadows dynamically is expensive, because iOS has to draw the shadow around the exact shape of your view's contents. If you can, set the shadowPath property to a specific value so that iOS doesn't need to calculate transparency dynamically. For example, this creates a shadow path equivalent to the frame of the view:

yourView.layer.shadowPath = UIBezierPath(rect: yourView.bounds).cgPath

Alternatively, ask iOS to cache the rendered shadow so that it doesn't need to be redrawn:

yourView.layer.shouldRasterize = true

If you want to go down the rasterization route, you should make sure iOS caches the shadow at the same drawing scale as the main screen, otherwise it will look pixelated:

yourView.layer.rasterizationScale = UIScreen.main.scale

SPONSOR Tired of wasting time debugging your Swift app? Instabug’s SDK is here to help you minimize your debugging time by providing you with complete device details, network logs, and reproduction steps with every bug report. All data is attached automatically. It only takes a line of code to setup. Get started for free.

Available from iOS 3.2

Did this solution work for you? Please pass it on!

Other people are reading…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

MASTER SWIFT NOW
Buy Testing Swift Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let me know!

Average rating: 4.8/5

Click here to visit the Hacking with Swift store >>