lineDashPhase
The dash phase applied to the shape’s path when stroked. Animatable.
Declaration
var lineDashPhase: CGFloat { get set }Discussion
Line dash phase specifies how far into the dash pattern the line starts.
Default is 0.
The following code shows how you can create a “marching ant” effect by adding an animation to a shape layer that animates its lineDashPhase from 0 to the sum of the segment lengths of its lineDashPattern.
let shapeLayer = CAShapeLayer()
shapeLayer.strokeColor = UIColor.black.cgColor
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.lineWidth = 5
shapeLayer.lineDashPattern = [10,5,5,5]
let path = CGMutablePath()
path.addLines(between: [CGPoint(x: 0, y: 100),
CGPoint(x: 640, y: 100)])
shapeLayer.path = path
let lineDashAnimation = CABasicAnimation(keyPath: "lineDashPhase")
lineDashAnimation.fromValue = 0
lineDashAnimation.toValue = shapeLayer.lineDashPattern?.reduce(0) { $0 + $1.intValue }
lineDashAnimation.duration = 1
lineDashAnimation.repeatCount = Float.greatestFiniteMagnitude
shapeLayer.add(lineDashAnimation, forKey: nil)