Add Shadow to a Button in iOS8 with Swift

In iOS 8 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 Built for iOS8 with Xcode 6.

Update: Mar 1, 2017. The rewritten version in Swift for iOS 10.2 and Xcode 8.2.1 is available here.

Open Xcode and create a new Single View Application. For product name, use iOS8SwiftShadowButtonTutorial 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. In Xcode 6 view controllers are now square by default, so that you can create one user interface for multiple devices. In iOS8 you can layout the Storyboard using constraints and size classes. Since this app is only going to be for the iPhone, you can disable size classes. In the File Inspector untick Use Size Classes.

Choose Keep size class data for: iPhone, and click Disable Size Classes.

Add a Button to the main view and give it a title of "Shadow Tutorial". The Storyboard should look like this.

Open the Assistant Editor and make sure the ViewController.swift file is visible. Ctrl + drag from the Button to the ViewController class and create the following Outlet.

Change the viewDidLoad method to

override func viewDidLoad() {
  button.layer.shadowColor = UIColor.blackColor().CGColor
  button.layer.shadowOffset = CGSizeMake(5, 5)
  button.layer.shadowRadius = 5

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. Alsoe the shadowRadius property is set to 5 to round off the corners of the shadow a bit.

When you Build and Run, the drop shadow is not visible yet. To let it show we need to set the shadowOpacity property between 0.0 and 1.0. (1.0 is darkest). Add the following line to the end of the viewDidLoad method

button.layer.shadowOpacity = 1.0  

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

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