我正试图通过单击按钮向后循环一个数组。
我当前的代码很接近,但效果不好。
- (void)viewDidLoad {
self.imageNames = [NSArray arrayWithObjects:@"MyFirstImage", @"AnotherImage", nil];
currentImageIndex = 0;
[super viewDidLoad];
}
......什么有效:
- (IBAction)change {
UIImage* imageToShow = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[imageNames objectAtIndex:currentImageIndex] ofType:@"png"];
currentImageIndex++;
if (currentImageIndex >= imageNames.count) {
currentImageIndex = 0;
}
}
......以及什么不起作用:
- (IBAction)changeBack {
UIImage* imageToShow = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[imageNames objectAtIndex:currentImageIndex] ofType:@"png"];
currentImageIndex--;
if (currentImageIndex >= imageNames.count) {
currentImageIndex = 0;
}
}
非常感谢任何帮助!
谢谢!
答案 0 :(得分:1)
您需要先更改索引,然后获取图像。当向后移动时,您需要在消极时将索引重置为最大值(count-1):
- (IBAction)changeBack {
currentImageIndex--;
if (currentImageIndex < 0) { // was first image
currentImageIndex = imageNames.count-1; // last image
}
UIImage* imageToShow = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[imageNames objectAtIndex:currentImageIndex] ofType:@"png"];
}
要前进到下一张图片:
- (IBAction)change {
currentImageIndex++;
if (currentImageIndex >= imageNames.count) { // was last image
currentImageIndex = 0; // back to first image
}
UIImage* imageToShow = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[imageNames objectAtIndex:currentImageIndex] ofType:@"png"];
}
答案 1 :(得分:0)
也许在changeBack方法中,您应该更改此行代码以显示以下内容:
if (currentImageIndex <= 0) {
currentImageIndex = imageNames.count;
}
(假设当用户超过第一张图片时,他们会回到最后一张图片)