Question

I want to make custom UIView with border. Here is my code:

- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetLineWidth(context, 4.0);
    CGContextSetStrokeColorWithColor(context, [[UIColor blueColor] CGColor]);
    CGContextAddRect(context, self.frame);
    CGContextStrokePath(context);
}

And here is the result: enter image description here

All three UIView on this picture is my custom view, but only big UIView have the border. I don't understand why others have no border. What is wrong?

Was it helpful?

Solution

You need local coordinates. Change

CGContextAddRect(context, self.frame);

to

CGContextAddRect(context, self.bounds);

OTHER TIPS

  1. You didn't specify the classname for subviews

  2. why don't you try like this

    anyView.layer.borderColor = [UIColor redColor].CGColor;
    anyView.layer.borderWidth = 5.0f;
    
  3. Or add this method in your custom view

    -(void)awakeFromNib{
    
        [super awakeFromNib];
    
        self.layer.borderColor = [UIColor redColor].CGColor;
        self.layer.borderWidth = 5.0f;
    
    }
    

Yo have not added the path to your context

-(void)drawRect:(CGRect)rect
{
    [super drawRect:rect];

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGPathRef path = CGPathCreateWithRect(rect, NULL);
    [[UIColor blueColor] setStroke];
    CGContextSetLineWidth(context, 4.0);
    CGContextAddPath(context, path);
    CGContextDrawPath(context, kCGPathFillStroke);
    CGPathRelease(path);
}

Resolved! The problem was in self.frame for CGContextAddRect. It must be self.bounds to draw in my view.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top