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
Done =)
It works really well.
Thanks!
LikeLike
you are welcome~ =)
LikeLike
Hi Can we set
rounded corner border UIView
and simple rounded corner UIView
Thanks
Amit Battan
LikeLike
Hi Amit,
does the following post help?
iPhone – Round Image Corner
Kit
LikeLike
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
LikeLike
Thanks Aruna. but your code is not yet completed, could u post again?
LikeLike
You need to add the QuartzCore framework to your project.
LikeLike
ic. Thanks for your suggestion =)
LikeLike
@XCool thankx Broooo
LikeLike
you are welcome. =D
LikeLike
How to change the border color at run time ???
LikeLike
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.
LikeLike