Rounded Corners on a UIView with the iPhone SDK 3.0

An iPhone app with programmatically set cornerRadiusI’ve been doing a bit more iPhone development recently and one of the challenges we encountered was to control the background color of a UIView programmatically. Now this is a pretty simple thing to do until you decide you also want to round the corners of that view.

One option is of course to use an image as a background but this wouldn’t allow us to programmatically change the background color of the UIView.

After a bit of digging I finally came across the method cornerRadius delcared as the following:

@property CGFloat cornerRadius

The corner radius is a property of the layer which is a CALayer. In order to use this though you must be using iPhone SDK Version 3.0 or above and you must include QuartzCore/QuartzCore.h

Another tip was that the corner radius does not work until you set masksToBounds to true. With all of this combined the following snippet should allow you to create rounded rectangles on your UIViews.

//Includes
#import "QuartzCore/QuartzCore.h"

//To set the rounded corners
self.layer.masksToBounds = YES;
self.layer.cornerRadius = 5.0;
Advertisements

About Steve Smith
Software developer (often ruby, rails but I enjoy loads of languages), semantic tech. fanboy, skydiver, all round geek. Owner of dynamic:edge (hire us) the makers of CloudMailin.com

2 Responses to Rounded Corners on a UIView with the iPhone SDK 3.0

  1. Pingback: Rounded Corners with an arrow on a UIView with the iPhone SDK 3.0 « Steve @ DynamicEdge

  2. Scott Rapson says:

    Thanks for this. For some reason my corners wern’t rounding until I added

    myView.layer.masksToBounds = YES;

    Most other documentation misses this and goes straight into the corner radius.

    Thanks

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: