Search code examples
iosswiftxcodecashapelayer

Swift: How to set CAShapeLayer() progress value


I just create an IOS app where I implement a round progress bar with CAShapeLayer(). And know I want to set in each second the progress value to +1 is this posible? I would just like to create a progress bar like this one that leaps forward a value every second: Like this

Best Regards!


Solution

  • CAShapeLayer has animatable strokeStart and strokeEnd properties. You can directly set these and they will be animated automatically, or you can control the animation yourself like any other animatable CALayer property:

    let animation = CABasicAnimation(keyPath: "strokeEnd")
    animation.fromValue = 0
    animation.toValue = 1
    animation.duration = 1
    shape.add(animation, forKey: nil)
    

    This will fill the progress indicator in 1 second.

    For a stroke end animation to work, you can't use a CGPath which is just a circle - you need an arc with a start and an end, like this:

    let path = CGMutablePath()
    path.addArc(
        center: CGPoint(x: 150, y: 150),
        radius: 100,
        startAngle: -0.5 * .pi,
        endAngle: 1.5 * .pi,
        clockwise: false
    )