Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIImageView transition between different images with animation

i have this code which repeating fade in the same picture to the view controller forever

 override func viewDidAppear(_ animated: Bool) {
        let toImage = UIImage(named:"intro.png")
        UIView.transition(with: self.imageView,
                          duration:2,
                          options: [.repeat , .transitionCrossDissolve],
                          animations: { self.imageView.image = toImage},
                          completion: nil)


    }

Now i need it to such between four images every time fade in with different img for ever.

like image 337
Osama Fawzi Avatar asked Mar 08 '23 23:03

Osama Fawzi


1 Answers

How can you do it?

you will need:

  1. A timer
  2. A counter
  3. An array of for holding image names

    var images:[String] = []
    var timer = Timer()
    var photoCount:Int = 0

in viewDidLoad i did this for initialization.

images = ["1","2","3"]
imageView.image = UIImage.init(named: "1")
timer = Timer.scheduledTimer(timeInterval: 2.0, target: self, selector: #selector(onTransition), userInfo: nil, repeats: true)

And the magic method for doing this is below:

func onTransition() {
    if (photoCount < images.count - 1){
        photoCount = photoCount  + 1;
    }else{
        photoCount = 0;
    }

    UIView.transition(with: self.imageView, duration: 2.0, options: .transitionCrossDissolve, animations: { 
        self.imageView.image = UIImage.init(named: self.images[self.photoCount])
    }, completion: nil)
}

Don't forget to pull your imageView referrence outlet. :)

   @IBOutlet weak var imageView: UIImageView!
like image 176
elk_cloner Avatar answered Mar 11 '23 14:03

elk_cloner