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;

2 thoughts on “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. 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 comment