2010-06-13 113 views
1

我試圖通過單擊按鈕向後循環數組。向後循環通過NSArray

我目前的代碼很接近,但並不完美。

- (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; 
} 
} 

任何幫助,很高興地感謝!

謝謝!

回答

1

您需要先更改索引,然後獲取圖像。當退步需要索引重置爲最大值(計數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"]; 
} 
+0

謝謝!這就像一個魅力。 – dot 2010-06-14 23:34:53

0

也許在changeBack方法,你應該改變這行代碼顯示如下:

if (currentImageIndex <= 0) {
currentImageIndex = imageNames.count;
}

(當用戶獲取過去的第一個圖像這是假設,他們回到過去一個)

+0

這崩潰的應用程序。很奇怪。 – dot 2010-06-13 02:55:48