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 8.2.1 and built for iOS 10.2.

Open Xcode and create a new Single View Application.

Open Xcode and create a new Single View Application. For product name, use iOS10ShadowButtonTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and make sure only iPhone is selected in Devices.

Go to the Storyboard. Add a Button to the main view and give it a title of "Shadow Tutorial". Select the Button and click the Pin Auto Layout button on the bottom-right of the Storyboard. Pin the button at the top edge and select "Items of New Constraints" at the Update Frames section. Select "Add 1 Constraint".

Select the button and click the Align Auto Layout button. Select the "Horizontally in Container" checkbox and select "Items of New Constraints" at the Update Frames section. Select "Add 1 Constraint".

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() {
    super.viewDidLoad()
        
    button.layer.shadowColor = UIColor.black.cgColor
    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 iOS10ShadowButtonTutorial at the ioscreator repository on Github