iPhone – UIView with Border

The border of the view could be drawn in the drawRect method in the view. Here is an example.

1. Create a UIView subclass (ex. UIViewWithBorder)

2. Construct the drawRect method In the UIViewWithBorder.m as follow

- (void)drawRect:(CGRect)rect {
	/* Set UIView Border */
	// Get the contextRef
	CGContextRef contextRef = UIGraphicsGetCurrentContext();
	// Set the border width
	CGContextSetLineWidth(contextRef, 5.0);
	// Set the border color to RED
	CGContextSetRGBStrokeColor(contextRef, 255.0, 0.0, 0.0, 1.0);
	// Draw the border along the view edge
	CGContextStrokeRect(contextRef, rect);


3. Add the new view in the view controller

#import <UIKit/UIKit.h>
@class UIViewWithBorder;

@interface SampleViewController : UIViewController {
	UIViewWithBorder *viewWithBorder;

@property(nonatomic, retain) UIViewWithBorder *viewWithBorder;




#import "SampleViewController.h"
#import "UIViewWithBorder.h"

@implementation SampleViewController
@synthesize viewWithBorder;

- (void)viewDidLoad {
	[super viewDidLoad];
	self.viewWithBorder = [[UIViewWithBorder alloc] initWithFrame:CGRectMake(100.0, 100.0, 50.0, 50.0)];
	self.viewWithBorder.backgroundColor = [UIColor whiteColor];
	[self.view addSubview:self.viewWithBorder];

- (void)dealloc {
	[self.viewWithBorder release];
	[super dealloc];



4. Try it out

Done =)

13 thoughts on “iPhone – UIView with Border”

  1. If you do not want to bother with CGGraphics.. use following two lines…

    yourview.layer.borderWidth = 1;
    yourview.layer.borderColor = [[UIColor grayColor] CGColor];

    and include this in header file



    1. can you elaborate more about what do u want to implement?

      for example, you may add a UIButton and implement the click action to change the border color when it is pressed.


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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.