2

Well, I have a UIImageview in one of my views. I would like to change the image every 10 seconds, but I don't have any idea of how can I make it.

Any suggestion?

sergiocg90
  • 489
  • 2
  • 11
  • 24

3 Answers3

19

Create array of images first.

NSArray *images = [NSArray arrayWithObjects:[UIimage imagenamed:@"image1.png"],[UIimage imagenamed:@"image2.png"],[UIimage imagenamed:@"image3.png"],[UIimage imagenamed:@"image4.png"]]];

Then set array to UIImageViews "animationImages"property

imageView.animationImages = images;

Set time for animation.

imageView.animationDuration = 10;

Start animation..

[imageView startAnimating];

To stop animation just do this

[imageView stopAnimating];

Pretty simple..

rakeshNS
  • 4,227
  • 4
  • 28
  • 42
  • +1 for correct answer - no need for reinventing the wheel for such task. – Till Apr 29 '12 at 09:48
  • 1
    Looks like this could cause memory problems if images are big, but this is really best solution for small images – Lope Apr 29 '12 at 09:50
4

You will need to use timer.

NSTimer *timer = [NSTimer timerWithTimeInterval:10 target:self selector:@selector(changeImage) userInfo:nil repeats:true];

and implement method for changing image:

- (void) changeImage {
    imageView.image = newImage;
}

You can put this timer into ViewController containing your ImageView or you you can subclass ImageView and let it manage its image itself (especially useful if there are more independent imageview that need to change its image

Lope
  • 5,388
  • 4
  • 30
  • 40
2

For Swift 4 place Timer.scheduledTimer call in viewWillAppear or viewDidAppear:

Timer.scheduledTimer(timeInterval: 10,
                         target: self,
                         selector: #selector(self.changeView),
                         userInfo: nil,
                         repeats: true)

and for changeView function change image

@objc func changeView() {
//change image in this function
}
kazi.munshimun
  • 2,168
  • 19
  • 17