NSTimer change image iPhone Programming

2019-03-07 02:52发布

问题:

How to change images periodically using NSTimer in iPhone progranmming?

I create an image view for loading images.

I want to display images in imageview and periodically change images by using NSTimer.

回答1:

import the images you like to your bundle application called them image1.png, image2.png image3.png and so on....

Add UIImageview in interface builder call it (reference) "theImage"

in the H file:

@interface delme3ViewController : UIViewController {

    UIImageView *theImage;
    int imageCount;
}
@property (nonatomic, retain) IBOutlet UIImageView *theImage;

@end

in the M file:

- (void)viewDidLoad
{
    [super viewDidLoad];
    [NSTimer scheduledTimerWithTimeInterval:1 
                                     target:self 
                                   selector:@selector(animateFunction) 
                                   userInfo:nil 
                                    repeats:YES];
    imageCount = 1;

}

-(void)animateFunction
{
    NSLog(@"Timer heartbeat %i",imageCount);
    imageCount = imageCount + 1;
    NSString *imageName = [NSString stringWithFormat:@"image%i.png"];
    [theImage setImage:[UIImage imageNamed:imageName]];
}


回答2:

Instead of using NSTimer, I would just use an arrary of UIImages and animate them. See the documentation from here.



回答3:

you can also use array of image names rather renaming images in your bundle. :)