Author Topic: How do I use animated images with the image view control in iOS?  (Read 9127 times)

kjmcneish

  • Administrator
  • *****
  • Posts: 719
    • View Profile
There are two main ways to use animated images with an image view. You can either use the image view's animationImages property or its image property.

1. Using the animationImages Property

First, you need to create an array of your images and store that array in the image view's animationImages property. Afterwards, you can set the animation duration and repeat count and then call startAnimating on the image view:

Code: [Select]
self.myImageView.animationImages =   [UIImage(named:"SBW1.png")!,
UIImage(named:"SBW1.png")!,
UIImage(named:"SBW2.png")!,
UIImage(named:"SBW3.png")!,
UIImage(named:"SBW4.png")!,
UIImage(named:"SBW5.png")!]

self.myImageView.animationDuration = 3.0
self.myImageView.animationRepeatCount = 5
self.myImageView.startAnimating()

2. Using the image Property

If you have an animation that repeats continuously, you can use the image view's image property. You can dynamically create an animated image from a set of images that end in sequentially incrementing numbers. For example, assuming images named SBW1, SBW2, SBW3, etc:

Code: [Select]
self.myImageView.image =
UIImage.animatedImageNamed("SBW", duration: 3.0)

The animatedImageNamed method of the UIImage class generates an animated image from the SBW1, SBW2, SBW3, etc. files. You then store the animated image in the image property, specifying the animation duration. When you do this, the animation starts immediately. There's no way to specify the animation's repeat count using this methodology, but you can stop the animation by storing a nil to the image view' image property.

All the best!
Kevin McNeish
Author of Learn to Code in Swift: https://itunes.apple.com/us/book/learn-to-code-in-swift/id942956811?mt=11