Search code examples
iosobjective-cuiviewuibezierpathcashapelayer

How to add a circleView progress to an UIView expanding to all UIView?


I have setup a UIView using constraints in a storyboard, and I want to add a circle progress to this view using CAShapeLayer with a UIBezierPath.

I have added this correctly, but the circle isn't expanded to all the view. i call this in my viewDidLoad function. My view has constraints to asjust height top-x view and width.

- (void)viewDidLoad {
[super viewDidLoad];

CAShapeLayer *borderLayer = [CAShapeLayer layer];
borderLayer.fillColor = [UIColor whiteColor].CGColor;
CGFloat lineWidth = 4;

CGRect rect = CGRectMake(lineWidth+lineWidth/2, lineWidth+lineWidth/2, self.myView.bounds.size.width/2, self.myView.bounds.size.height/2);
borderLayer.path = [UIBezierPath bezierPathWithOvalInRect:rect].CGPath;
borderLayer.strokeColor = [[UIColor redColor] CGColor];
borderLayer.lineWidth = lineWidth;
[borderLayer setFillColor:[UIColor clearColor].CGColor];
[self.myView.layer addSublayer:borderLayer];
}

The circle progress isn't resized to the UIView, and it is shown like this:

enter image description here

How can I draw this occupying the whole UIView like this:

enter image description here


Solution

  • 1 - Your view's frame will not have been set yet in viewDidLoad. You need to move this code into viewDidLayoutSubviews or later in the view controller's lifecycle.

    Related Question:

    Why am I having to manually set my view's frame in viewDidLoad?

    Apple Docs on view controller lifecycle: https://developer.apple.com/library/content/referencelibrary/GettingStarted/DevelopiOSAppsSwift/WorkWithViewControllers.html#//apple_ref/doc/uid/TP40015214-CH6-SW1

    2 - Change this:

    CGRect rect = CGRectMake(lineWidth+lineWidth/2, lineWidth+lineWidth/2, self.myView.bounds.size.width/2, self.myView.bounds.size.height/2);
    

    to this:

    CGRect rect = CGRectMake(lineWidth/2, lineWidth/2, self.myView.bounds.size.width - lineWidth, self.myView.bounds.size.height - lineWidth);
    

    Result (I used slightly different lineWidth and view size for my testing):

    enter image description here