FREE: Watch my new YouTube videos, Xcode in 20 Seconds! >>

How to create a marching ants effect using lineDashPhase

Paul Hudson       @twostraws

“Marching ants” is the informal name used for animation of a selection: you see a dashed line around whatever you selected, and the dashes slowly move around the selection to show that it’s active.

iOS can achieve most of this effect for you when you’re using a CAShapeLayer. To try it out, first create a shape layer with a dashed stroke like this:

let layer = CAShapeLayer()
let bounds = CGRect(x: 50, y: 50, width: 250, height: 250)
layer.path = UIBezierPath(roundedRect: bounds, byRoundingCorners: .allCorners, cornerRadii: CGSize(width: 20, height: 20)).cgPath
layer.strokeColor = UIColor.black.cgColor
layer.fillColor = nil
layer.lineDashPattern = [8, 6]
view.layer.addSublayer(layer)

Now you need to create a CABasicAnimation to animate the lineDashPhase property. Annoyingly, the lineDashPattern – the part that describes the way the dashed are drawn – is actually an array of NSNumber so we need to boil it down to an integer with code like this:

layer.lineDashPattern?.reduce(0) { $0 - $1.intValue } ?? 0

With the line dash pattern used above – 8, 6 – that will result in toValue being set to 14.

Here’s the animation you need to give the above shape layer a marching ants effect:

let animation = CABasicAnimation(keyPath: "lineDashPhase")
animation.fromValue = 0
animation.toValue = layer.lineDashPattern?.reduce(0) { $0 - $1.intValue } ?? 0
animation.duration = 1
animation.repeatCount = .infinity
layer.add(animation, forKey: "line")

I used .infinity for the repeat count so that it lasts forever.

Sponsored You’re already busy updating your app for Swift 4.2 and iOS 12, so why not let Instabug help you find and fix bugs? Add just two lines of code to your project and receive comprehensive reports with all the feedback you need to ship a world-class app – click here to learn more!

Available from iOS 3.2

Did this solution work for you? Please pass it on!

Other people are reading…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

Upgrade your apps!

Take on Core ML, ARKit, PDFKit, Core NFC, and more all in one book that's packed with practical projects!

MASTER SWIFT NOW
Buy Testing Swift Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let me know!

Average rating: 4.0/5

Click here to visit the Hacking with Swift store >>