0

I need to animate between images in a UIImageView. So after research I came out with this class:

    import UIKit

    class GzImageView: UIImageView {

    var imageCollection:[UIImage]? //images to show
    var count:Int = 0 // images counter

    func animate(){
        //when Counter get last image set it to the first one
        if self.count >= self.imageCollection?.count {
            self.count = 0
        }
        //get the image to show
        let img = self.imageCollection![self.count]
        //animate the transition
        UIView.transitionWithView(self,
            duration: 1.0,
            options: UIViewAnimationOptions.TransitionCrossDissolve,
            animations: { self.image = img }) //set the new image
            { (Bool) -> Void in
            self.animate() //Direct recursion
            self.count++
        }
    }                     
 }

And I use it that way:

let imgView = GzImageView(frame: CGRectMake(30, 100, 200, 200))
imgView.imageCollection = ["cake.png","bag.png","hat.png"].map { name -> UIImage in UIImage(named:name)!}
imgView.animate()

It works fine when I use as an UIView subview. But I need to use this as a UICollectionViewCell subview. And as a UICollectionViewCell subview it doesn't work properly. When I change to other UIView and came back to UICollectionView images start to blink very fast.

I couldn't figure out the problem, so I'm looking for another way to get this functionality.

Do you guys have another way to do that or know how to fix that?

Sebastian
  • 6,154
  • 5
  • 33
  • 51

2 Answers2

-1

For Swift 3.0.1 try https://stackoverflow.com/a/42710002/4935811:

UIView.transition(with: self.imageView,
          duration:0.5,
          options: .transitionCrossDissolve,
          animations: { self.imageView.image = newImage },
          completion: nil)

Reference: https://gist.github.com/licvido/bc22343cacfa3a8ccf88

Community
  • 1
  • 1
Sour LeangChhean
  • 7,089
  • 6
  • 37
  • 39
-2

You can do it easily in this way:

var animationDuration = 3;

            imageView.animationImages = imageSet;
            imageView.animationDuration = NSTimeInterval(animationDuration);
            imageView.startAnimating();

here imageSet in array of UIImage objects.

Sumit Jain
  • 146
  • 1
  • 9
  • It works fine, but this code doesn't have the fade effect between the animations. Do you know to add this effect in this implementation ? – Sebastian Aug 28 '15 at 13:39