Add Shadow to a Button iOS Tutorial

Every View has a backing layer property. This layer has properties for performing animations and transforms, but also for rendering options. In this tutorial the layer property will be used to create a drop shadow. This tutorial is made with Xcode 10 and built for iOS 12.

Open Xcode and create a new Single View App.

For product name, use iOSShadowButtonTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and choose Next.

Go to the Storyboard. Add a Button to the main view and give it a title of "Shadow Tutorial".  Select the Resolve Auto Layout Issues button and select Reset to Suggested Constraints.

The Storyboard should look like this.

Select the Assistant Editor and make sure the ViewController.swift file is visible. Ctrl-drag or right-click-drag from the Button to the ViewController class and create the following Outlet.

Change the viewDidLoad method to 

override func viewDidLoad() {
    button.layer.shadowColor =
    button.layer.shadowOffset = CGSize(width: 5, height: 5)
    button.layer.shadowRadius = 5
    button.layer.shadowOpacity = 1.0  

Every View has a layer property which you can use to create drop shadows. Here we set the color to black and we give the shadow a offset of 5 x 5.  The shadowRadius property is set to 5 to round off the corners of the shadow a bit. To show the shadow we need to set the shadowOpacity property between 0.0 and 1.0. (1.0 is darkest). 

Build and run the project, the drop shadow is visible beneath the button.

You can download the source code of the iOSShadowButtonTutorial at the ioscreator repository on Github