Add Shadow to a Button

With the QuartzCore framework you can add some effects to your objects using the layer property. In this tutorial we will create a drop shadow on a UIButton.

Update: Sep 24, 2014. The rewritten tutorial in Swift for iOS 8 and Xcode 6 is available here.

Open Xcode and create a new Single View Application. For product name, use ShadowButtonDemo and then fill out the Organization Name, Company Identifier and Class Prefix fields with your customary values. Make sure only iPhone is selected in Devices, and that the Use Storyboards checkbox is deselected and Use Automatic Reference Counting checkbox is selected.

For this project we need the QoartzCore framework, so navigate to the project options and in the Linked Frameworks and Libraries section add the framework.

Next , Let's create our User Interface. Go to ViewController.xib. Drag a Button to the main View and Give it a sample text of "Shadow Demo". The main View should look like this.

In ViewController.m in the interface section declare the following property.

@interface ViewController ()

@property (nonatomic,strong) IBOutlet UIButton *button;


Go back to ViewController.xib. Select the Assistant Editor. On the right side select ViewController.m. Ctrl-click and drag from the Button to the IBOutlet button property in ViewController.m.

Change the viewDidLoad method to

- (void)viewDidLoad 
[super viewDidLoad];

self.button.layer.shadowColor = [UIColor blackColor].CGColor;
self.button.layer.shadowOffset = CGSizeMake(15.0f,15.0f);
self.button.layer.masksToBounds = NO;
self.button.layer.shadowRadius = 5.0f;

Every object 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 15x15. When you want to create a drop shadow the masksToBounds property needs to be set to NO. Finally we set the shadowRadius property 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

self.button.layer.shadowOpacity = 1.0;

Build and Run, you should see the drop shadow.

You can download the source code of the ShadowButtonDemo at the ioscreator repository on github.