Animated Images on SwiftUI 🍿

Jobe Diego Dylbas dos Santos
2 min readApr 24, 2020

It's been a couple of months that I'm learning SwiftUI, a new declarative framework to build apps for the Apple Environment. Yes, you're reading properly, SwiftUI could be used to build apps for every Apple device.

The SwiftUI workflow could be difficult for those familiar only with UIKit, but using React similar concepts, Apple comes close to the most popular web UI frameworks. In fact, this new framework increases the interface building speed, especially for those who like to build only by code. Although, since SwiftUI is very new, there is a lack o documentation and examples of more complex components.

In one of my SwiftUI projects, I had to show a video animation, but without the properties of AVPlayer, like volume, full screen and etc. In that case particularly, my approach was to show the video as a frame sequence.
Searching the web I only found ways to create this effect using UIViewRepresentable, a way to encapsulate UIView to be shown in SwiftUI.
However, it was very complex for a simple thing, so in this tutorial you will learn how to show an image frame by frame in SwiftUI.

First we create an image property of our view structure as optional. This will prevent to show an image that doesn't exist and we be able to not pass an image as a parameter when we instantiate the view. The second property of our view is an array with the image names that will be shown. It's very important that the image names should be in the appearing order.

After that, we create a function that will animate this image. Let's call this function animate. The first idea is to create a loop, but we have to wait a little amount of time to change the image to create the movie. So, to create this effect we use the Timer.scheduledTimer will execute the code block below after each amount of time. In this way, the code will iterate through imageNames array.

Okay, if we call our function animate when our image appear, it will not work. This occurs because the first image doesn't exist and the loop never will happen. To solve that we encapsulate our image on a Group, and call animate when the Group appears. So the final code is:

To use AnimatedImage just call on any other View passing an array of the image names.

To an even more custom AnimatedImage, like number of iterations, idle and etc, you can find the Swift Package here. If you like this tutorial, please give a Clap and follow me on Github, Twitter and LinkedIn.

Thank you and wash your hands 👏!

--

--

Jobe Diego Dylbas dos Santos

Graduando de Ciência da Computação pela UFRGS e apaixonado pela influência da tecnologia na sociedade.