Circular progress in swift

ios, progress-bar, swift, uiview

Solution

For Swift 4

Declare two CAShapeLayers. One for actual circle and another for progress layer.

func createCircularPath() {
    let circleLayer = CAShapeLayer()
    let progressLayer = CAShapeLayer()
    
    let center = self.view.center
    let circularPath = UIBezierPath(arcCenter: center, radius: 100, startAngle: -.pi / 2, endAngle: 2 * .pi, clockwise: true)

    circleLayer.path = circularPath.cgPath
    circleLayer.fillColor = UIColor.clear.cgColor
    circleLayer.strokeColor = UIColor.lightGray.cgColor
    circleLayer.lineCap = .round
    circleLayer.lineWidth = 20.0  //for thicker circle compared to progressLayer

    progressLayer.path = circularPath.cgPath
    progressLayer.fillColor = UIColor.clear.cgColor
    progressLayer.strokeColor = UIColor.blue.cgColor
    progressLayer.lineCap = .round
    progressLayer.lineWidth = 10.0
    progressLayer.strokeEnd = 0

    view.addSublayer(circleLayer)
    view.addSublayer(progressLayer)

    let progressAnimation = CABasicAnimation(keyPath: "strokeEnd")
    progressAnimation.toValue = 1
    progressAnimation.fillMode = .forwards
    progressAnimation.isRemovedOnCompletion = false
    
    progressLayer.add(progressAnimation, forKey: "progressAnim")
}

Problem

I am trying to make a simple circular progress bar in swift. What I have failed to do so far is, the progress should start at the top of the circle (at the moment it is starting at the 90 degree point). I would also like to have a circular line under the progress line that should be thicker than the progress line and have a different color as well.. Can anyone put me in the right direction towards my wishes? Here is my function: ``` func animateView() { let circle = viewProgress // viewProgress is a UIView var progressCircle = CAShapeLayer() let circlePath = UIBezierPath(ovalInRect: circle.bounds) progressCircle = CAShapeLayer () progressCircle.path = circlePath.CGPath progressCircle.strokeColor = UIColor.greenColor().CGColor progressCircle.fillColor = UIColor.clearColor().CGColor progressCircle.lineWidth = 5.0 circle.layer.addSublayer(progressCircle) let animation = CABasicAnimation(keyPath: "strokeEnd") animation.fromValue = 0 animation.toValue = 1.5 animation.duration = 1 animation.fillMode = kCAFillModeForwards animation.removedOnCompletion = false progressCircle.addAnimation(animation, forKey: "ani") } ``` Igor this is how it looks:

Original source