Reputation: 139
I have a view controller based app that contains several views that I display/hide depending on some logic. I would like to draw a rectangle which will be the size of the UIView in order to give it like a frame/border shape.
I'm having issue drawing a rectangle. I understand that the following code should do it but I'm not sure why this method is not being called or triggered. I also didn't see the (void)drawRect:(CGRect)rect method generated anywhere so I placed it myself. Not sure what I'm missing here..
- (void)drawRect:(CGRect)rect;
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetRGBStrokeColor(context, 1.0, 1.0, 0.0, 1.0); // yellow line
CGContextBeginPath(context);
CGContextMoveToPoint(context, 50.0, 50.0); //start point
CGContextAddLineToPoint(context, 250.0, 100.0);
CGContextAddLineToPoint(context, 250.0, 350.0);
CGContextAddLineToPoint(context, 50.0, 350.0); // end path
CGContextClosePath(context); // close path
CGContextSetLineWidth(context, 8.0); // this is set from now on until you explicitly change it
CGContextStrokePath(context); // do actual stroking
CGContextSetRGBFillColor(context, 0.0, 1.0, 0.0, 0.5); // green color, half transparent
CGContextFillRect(context, CGRectMake(20.0, 250.0, 128.0, 128.0)); // a square at the bottom left-hand corner
}
Upvotes: 0
Views: 3270
Reputation: 6718
First you create a class(YourView
) which is subclass of UIView
. You implement code in your viewController.
- (void)viewDidLoad
{
YourView *temp = [[YourView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
[self.view addSubview:temp];
}
You write your method(- (void)drawRect:(CGRect)rect
) in YourView.m
file.
Try like this. I think it will helpful to you.
Upvotes: 0
Reputation: 16400
Just guessing, but do you tell the UIView
to redisplay itself?
[myUIView setNeedsDisplay];
Only then does the drawRect:
get called.
Upvotes: 0
Reputation: 4594
If all you need to do is add a simple rectangular border, just do the following in your viewWillAppear:
for your view controller.
- (void) viewWillAppear:(BOOL)animated
{
//Simple border on the main view
self.view.layer.borderColor = [UIColor redColor].CGColor;
self.view.layer.borderWidth = 2;
//Or a simple rectangle to place at x,h within the main view
UIView *test = [[UIView alloc] initWithFrame:CGRectMake(x, y, width, height)];
test.backgroundColor = [UIColor redColor];
[self.view addSubview:test];
}
Hope this helps!
Upvotes: 2