用NSTimer更改UIImage?

所以我的这个项目的最终目标是有一对夫妇的图像和UIImageview并有图像每10秒更改一次,我目前有NSTimer设置和图像数组,但我不知道如何利用这两个NSTimer和UIImage视图一起。 到目前为止,这是我的:

在我的.h:

 #import <UIKit/UIKit.h> @interface HomeViewController : UIViewController { NSTimer *myTimer; IBOutlet UIImageView *imageview; } @property (nonatomic, strong) NSArray *images; 

而在我的

 - (void)viewDidLoad { [super viewDidLoad]; myTimer = [NSTimer scheduledTimerWithTimeInterval:10.00 target:self selector:@selector(changeImage) userInfo:nil repeats:YES]; } - (void)changeImage { _images = @[@"Background 3.png", @"Background.png", @"Background 2.png", @"Background 4.png", @"Background 5.png"]; //stuck here, how do I change the image using the NStimer interval???? } 

所以,现在你已经看到了代码,我无法弄清楚changeImage方法里面应该做什么。 只是在审查我想要的数组中的5个图像循环每10秒在UIImage视图。 我已经尝试了很多的select,我只是不能把它整理出来。 任何帮助将不胜感激。

你可以简单地使用下面的代码来做到这一点。

 - (void)viewDidLoad { [super viewDidLoad]; _images = @[@"Background 3.png", @"Background.png", @"Background 2.png", @"Background 4.png", @"Background 5.png"]; myTimer = [NSTimer scheduledTimerWithTimeInterval:10.00 target:self selector:@selector(changeImage) userInfo:nil repeats:YES]; } - (void)changeImage { static int counter = 0; if([_images count] == counter+1) { counter = 0; } imageview.image = [UIImage imageNamed:[_images objectAtIndex:counter]; counter++; } 

把这个放在changeImage中

 imageview.image = [_images objectAtIndex:self.currentIndex]; if (self.currentIndex == (_images.count-1)) { self.currentIndex = 0; } else { self.currentIndex++; } 

这在.h

 @property (assign) NSInteger currentIndex; 

也在viewDidLoad呃一些设置:

 self.currentIndex = 0; 

有几种方法可以做到这一点,我build议用户使用NSTimeruserInfo属性,而不是保留一个静态variables。 这样你就不必担心跟踪一个单独的计数variables,你可以启动它,它会运行(尽pipe你可能想要跟踪它,因为其他原因):

 - (void)viewDidLoad { [super viewDidLoad]; _images = @[@"Background 3.png", @"Background.png", @"Background 2.png", @"Background 4.png", @"Background 5.png"]; myTimer = [NSTimer scheduledTimerWithTimeInterval:10.00 target:self selector:@selector(changeImage:) userInfo:[NSNumber numberWithInt:0] repeats:YES]; } 

然后你的callback:

 - (void)changeImage: (NSTimer *)timer { int index = timer.userInfo.intValue; imageview.image = [UIImage imageNamed:[_images objectAtIndex:index]; timer.userInfo = [NSNumber numberWithInt: (index + 1) % _images.count]; }