DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • A Developer’s Guide to Multithreading and Swift Concurrency
  • Automate Developer Routine With Swift in iOS Development
  • How to Make a Picture-in-Picture Feature in iOS App Using AVFoundation
  • Hexagonal Architecture in the Frontend: A Real Case

Trending

  • AI’s Role in Everyday Development
  • Fixing Common Oracle Database Problems
  • Teradata Performance and Skew Prevention Tips
  • Scaling Mobile App Performance: How We Cut Screen Load Time From 8s to 2s
  1. DZone
  2. Coding
  3. Frameworks
  4. How to Make iOS Animations With UIImageView in Swift

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.

By 
Marco Santarossa user avatar
Marco Santarossa
·
Oct. 18, 17 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
15.2K Views

Join the DZone community and get the full member experience.

Join For Free

Introduction

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’s nil.
  • open var highlightedAnimationImages: [UIImage]? This array contains the images to show in the animation when the view is highlighted. By default, it’s nil.
  • 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 is 0.
  • 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.

Image title

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:

  1. Set the property image to show the current Chromecast state (cast_connected/cast_disconnected).
  2. 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.

Icon Swift (programming language)

Published at DZone with permission of Marco Santarossa, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • A Developer’s Guide to Multithreading and Swift Concurrency
  • Automate Developer Routine With Swift in iOS Development
  • How to Make a Picture-in-Picture Feature in iOS App Using AVFoundation
  • Hexagonal Architecture in the Frontend: A Real Case

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: