How to change the border style of an IOS UI Element, adding rounded corners and colour.

In iPhone development, a common thing you need to do is style the border of a UI element, be it a text field, label, table, or any other UI element.

This is a quick run through on how to change the border style of a UI element in Objective-C by accessing the CALayer property.

To access the layer property of a view you first need to include the QuartzCore framework. #import <QuartzCore/QuartzCore.h>

Without going into to much detail, QuartzCore is an Objective-C framework that creates simple animations on UI elements [IphoneDevWiki.net]. Quartz specifically refers to a pair of Mac OS technologies part of the Core Graphics Framework.

Once you have done this, you will be able to access the layer property.

UILabel *myLabel; myLabel.layer.<layerAttributeName>

Note: I have used a UILabel element, but this same technique can be applied to most UI elements.

The three layer properties we will look at today are borderColor, borderWidth, and cornerRadius.

borderWidth and cornerRadius both take floats as input, and are fairly self-explanatory, have a play around with different values to find one that suits your need.

myLabel.layer.borderWidth = 1.0f; myLabel.layer.cornerRadius = 5.0f;

The borderColor is only slightly more complex. Instead of using a UIColor, it uses a CGColor. CGColor is part of the QuartzCore framework, and defines a set of colour components (red, green, blue) that uniquely define a colour, and a colour space that defines how those colours should be interpreted.

For now, we will just access the CGColor property on a UIColor object, however you could also define your own CGColorRef by defining each of the three colours and the alpha(rgba), defining a CGColorSpaceRef, and then applying the colour definitions and the colour space to a new CGColorRef object. Stack Overflow has a good tutorial on how to do this.

myLabel.layer.borderColor = [UIColor blueColor].CGColor;

Using these three properties in conjunction you can now change the border style of UI elements.

Full code listing.

#import <QuartzCore/QuartzCore.h>
UILabel *myLabel;
myLabel.layer.borderWidth = 1.0f;
myLabel.layer.cornerRadius = 5.0f;
myLabel.layer.borderColor = [UIColor blueColor].CGColor;


  • http://www.mystickers.com.au/ labels

    This is the first time I’ve been to your site. Thanks for providing more details.

  • Artful Dodger

    It burns when I pee.

We'd love to
hear from you

We've prepared a simple project planner to get started.

Lets get started

Or send us a
message

Phone: (07) 3878 1151

Address: Office 2, 59 Hardgrave Rd,
West End, Brisbane, 4101, QLD, Australia

  • This field is for validation purposes and should be left unchanged.
css.php