circle progress in swift

Here's an example code for a circular progress view:

main.swift
import UIKit

class CircleProgressView: UIView {

    fileprivate var shapeLayer = CAShapeLayer()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupShapeLayer()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupShapeLayer()
    }
    
    fileprivate func setupShapeLayer() {
        let circlePath = UIBezierPath(ovalIn: bounds)
        shapeLayer.path = circlePath.cgPath
        shapeLayer.strokeColor = UIColor.red.cgColor
        shapeLayer.fillColor = UIColor.clear.cgColor
        shapeLayer.lineWidth = 10.0
        shapeLayer.strokeEnd = 0.0
        layer.addSublayer(shapeLayer)
    }
    
    func animate(to progress: CGFloat) {
        let animation = CABasicAnimation(keyPath: "strokeEnd")
        animation.fromValue = shapeLayer.strokeEnd
        animation.toValue = progress
        animation.duration = 1.0
        shapeLayer.add(animation, forKey: "animateCircle")
        shapeLayer.strokeEnd = progress
    }
}
1024 chars
36 lines

This code creates a UIView subclass named CircleProgressView that contains a CAShapeLayer that draws a circle. The animate(to:) function takes a progress between 0.0 to 1.0 and animates the stroke of the circle accordingly.

To use this view, simply add it to your view hierarchy and call animate(to:) to update the progress. For example:

main.swift
let circleView = CircleProgressView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
view.addSubview(circleView)

circleView.animate(to: 0.5) // animates the circle to 50% progress
184 chars
5 lines

gistlibby LogSnag