Mega Bundle SALE is ON! Get ALL of our amazing iOS app codebases at 95% OFF discount šŸ”„

iOS has built-inĀ support for adding shadows to UIView components. All you need to do in order to add a shadow to a UIView object is to set the shadow properties of the view’s layer. Shadows are a powerful user interface design element, making the visual components stand out by giving them a 3D look and feel. In order to display a shadow in Swift, iOS allows you to specify its color, opacity, offset and radius. Our recommendation is to try out different values for these variables, to see for yourself what are they exactly.

Since we often encounter the need of adding a shadow to a UIView while building the best iOS app templates that will help you make your own mobile app extremely easy, we thought to share the Swift source code of how we are dropping shadows to our UI views. Without further ado, here’s the UIView extension you can plug into your code to support adding shadows:

import UIKit

extension UIView {
    func dropShadow(scale: Bool = true) {
        layer.masksToBounds = false
        layer.shadowColor = UIColor.black.cgColor
        layer.shadowOpacity = 0.2
        layer.shadowOffset = .zero
        layer.shadowRadius = 1

        layer.shouldRasterize = true
        layer.rasterizationScale = scale ? UIScreen.main.scale : 1
    }
}

Just add this extension to your Swift codebase, and then you can add a shadow to any UIView, by simply calling the dropShadow method, like this:

view.dropShadow()

A small caveat we encounter is that this won’t work directly on UICollectionViewCell objects, due to how a collection view is laying out its recyclable cells. In order to add a shadow to a collection view cell in Swift, we recommend creating a container view for that cell, make it a couple of pixels smaller than the cell and add a shadow to that UIView container instead. If you’re using auto layout, creating a container view and setting up its constraints is very straightforward. Otherwise, you might need to make more changes to your view layer structure.

Got any other tips to share on how to add a shadow to a UIView in Swift? Let us know in the comments. We hope this has been helpful.

Feel free to check out the source code on Github.


Leave a Reply

Your email address will not be published. Required fields are marked *

Shopping Cart