Code a Loading Animation with CADisplayLink in Swift & Xcode without CocoaPods

Max Nelson  (maxcodes)
HackerNoon.com
3 min readJun 3, 2019

--

Use CADisplayLink to create a dope loading animation for your iOS apps.

My name is Max, and I run maxcodes.io. Nice to finally meet you.

I recorded a video on this exact topic found here.

Step 1. Create a circle

Create a view and constrain that junk on the screen with the following lines of code.

the following lines of code.

Step 2. Create a CADisplayLink instance

  • Before I explain, declare an instance of CADisplayLink and attach it to a method with the following lines of code.
  • Create a value CGFloat variable we can use to modify the view’s alpha or opacity upon every frame update.
  • Increment value by one and print the value divided by one-hundred. You should see an output like this, which goes on and on.

I use CADisplayLink quite a bit in my latest course found here.

What we are doing here, is we are adding a CADisplayLink to the main thread on the device which will then be synchronized with the refresh rate of the display. You can read all about this within the Apple Developer Documentation on CADisplayLink here.

yes, these are the following lines of code. The output is pictured on the right.

Step 3 — Animate.

Think about what we could do here. We have the value going from 0 to 1 over a period of time.

We can apply, or pass this value to the withAlphaComponent method on UIColor when setting a color. This will allow us to slowly fade in any given color.

You can fade in the color with one single line of code, the line contained within the blue box in the following code image.

But if you want it to fade back and forth, you need to apply some basic logic which I explain 100% for free in the video version of this article found here.

ahh yes, the following lines of code; with output on the left of course.

Step 4 — The output is pictured in the gif above.

Ok, we are done, but what is step 4? Well, step 4 is optional. If you want to use CADisplayLink along with classes like CAShapeLayer, UIBezierPath, CABasicAnimation, and more to create complex animations from start to finish, then you’re gonna want to take my latest course, The iOS Development Animations Course — Swift 5 & Xcode 10

Thanks, Dawg.

I truly appreciate those of you who watch my videos, read my articles, and take my courses.

To hear first of new article announcements, courses, and YouTube series, and vlogs, make sure to check out my website to hop on the dev list.

Thanks,

And as always, I will see you in the very next video.

-Max

--

--