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
UIViewWithBorder.m

...
- (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
SampleViewController.h

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

@interface SampleViewController : UIViewController {
	UIViewWithBorder *viewWithBorder;
}

@property(nonatomic, retain) UIViewWithBorder *viewWithBorder;

@end

 

SampleViewController.m

#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];
}

@end

 

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

    #import

    Like

    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.

      Like

Leave a comment

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