2010-06-13 7 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

0

아마도 changeBack 방법에 다음과 같은 표시하는 코드 줄을 변경해야합니다

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

(사용자가 첫 번째 이미지를지나 오면이 가정으로, 그들은 마지막으로 돌아갑니다 하나)

+0

이 응용 프로그램을 충돌 그. 매우 이상합니다. – dot