How to Make iOS Animations With UIImageView in Swift
Learn all about using UIImageView in Swift to create animations for your iOS mobile apps in this detailed walkthrough with a sample project to help you learn how.
Join the DZone community and get the full member experience.
Join For FreeIntroduction
When we speak about animations in iOS, we usually think of the static method animate
of UIView
or transition animations. In addition to this, UIKit
provides also the possibility to create animations with an UIImageView
using a series of images.
This article is split into two parts:
- Theoretical: Description of the public interface of
UIImageView
to create the animations. - Practical: A sample app to show how to create an animation using
UIImageView
.
Happy reading!
Public Interface
UIImageView
exposes some methods and properties to handle the animations:
open var animationImages: [UIImage]?
This array contains the images to show in the animation. By default, it’snil
.open var highlightedAnimationImages: [UIImage]?
This array contains the images to show in the animation when the view is highlighted. By default, it’snil
.open var animationDuration: TimeInterval
The time, in seconds, to complete a cycle of images. By default, it’s the number of images * 1/30th of a second.open var animationRepeatCount: Int
The number of times we want to repeat the animation.0
means infinite. The default value is0
.open func startAnimating()
Method to start the animation.open func stopAnimating()
Method to stop the animation.open var isAnimating: Bool { get }
Boolean information which indicates if the animation is running.
UIImageView
shows the animationImages
and highlightedAnimationImages
only when the animation is running. If we don’t run the animation, the UIImageView
shows the default image set in the property:
var image: UIImage?
Example
Now, we are ready to make an application using the UIImageView
for the animations.
In this example, we are going to use an UIImageView
to make a Chromecast icon animation:
Getting Started
In the next section, we are going to see all the steps to build the sample app. You can download the final project here.
The sample app is very plain. It has two UIKit
elements:
UIImageView
: We’ll use this component to show the Chromecast icon and its animation.UIButton
: The action of this button will start the simulated connection and disconnection of a Chromecast device.
Prepare Icons
Before starting coding, we need the icons to show. You can find the Chromecast icons set here.
Once we download the icons, we can add them to the project assets with the following names:
Prepare UI
The next step is creating the UI inside the initial view controller of Main.storyboard
:
Then, we can link the UI components to two IBOutlet
properties inside ViewController
:
@IBOutlet private weak var chromecastImageView: UIImageView!
@IBOutlet private weak var connectButton: UIButton!
Prepare Animation
At this point, we have to prepare the UIImageView
for the animation.
In ViewController
, we can setup chromecastImageView
inside the method viewDidLoad
:
override func viewDidLoad() {
super.viewDidLoad()
setupImageViewAnimation()
}
private func setupImageViewAnimation() {
chromecastImageView.animationImages = [#imageLiteral(resourceName: "cast_0"), #imageLiteral(resourceName: "cast_1"), #imageLiteral(resourceName: "cast_2")]
chromecastImageView.animationDuration = 1
}
With this configuration, we have an UIImageView
which is ready to animate the images cast_0
, cast_1
and cast_2
in one second.
If you don’t know #imageLiteral
, I would suggest you have a look at this article.
Trigger Animation
The last step is triggering the animation. First of all, we need a property to store the Chromecast state connected
/disconnected
:
enum CastState {
case connected
case disconnected
}
class ViewController: UIViewController {
private var castState = CastState.disconnected
// ...
Then, we must create a new IBAction
for connectButton
with the event touch up inside:
@IBAction private func onConnectButton(_ sender: Any) {
}
Now, we can add the implementation to trigger the Chromecast icon animation:
@IBAction private func onConnectButton(_ sender: Any) {
switch castState {
case .connected:
disconnect()
case .disconnected:
connect()
}
}
private func connect() {
// Disables the button to avoid user interaction when the animation is running
connectButton.isEnabled = false
chromecastImageView.startAnimating()
// Simulates a connection with a delay of 3 seconds
DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
self.chromecastImageView.stopAnimating()
// Enables the button to allow user interaction
self.connectButton.isEnabled = true
// Updates UI
self.toggleCastState()
}
}
private func disconnect() {
// Updates UI
toggleCastState()
}
private func toggleCastState() {
// Updates current Chromecast state
castState = castState == .connected ? .disconnected : .connected
// Updates button title
let buttonTitle = castState == .connected ? "Disconnect" : "Connect"
connectButton.setTitle(buttonTitle, for: .normal)
// Updates `UIImageView` default image
let image = castState == .connected ? #imageLiteral(resourceName: "cast_connected") : #imageLiteral(resourceName: "cast_disconnected")
chromecastImageView.image = image
}
We perform the animation only when we connect a new Chromecast device.
Conclusion
In the sample app, we used the UIImageView
for two purposes:
- Set the property
image
to show the current Chromecast state (cast_connected
/cast_disconnected
). - Run the Chromecast icon animation.
In some scenarios, we may not need the point 1. If we want to use UIImageView
only to show an animation, we can assign to the property image
an animation like this:
let images: [UIImage] = [#imageLiteral(resourceName: "cast_0"), #imageLiteral(resourceName: "cast_1"), #imageLiteral(resourceName: "cast_2")]
chromecastImageView.image = UIImage.animatedImage(with: images, duration: 1)
In this way, UIImageView
shows an infinite animation automatically. We don’t need to start it manually.
Published at DZone with permission of Marco Santarossa, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments