2012-01-27 25 views
2

對於iOS編碼來說是新的,所以這可能更像是一個語法問題。我想實現一個UIImageView加載一個圖像對象的數組。在右滑動,我想移動到數組中的下一個對象,並將其加載到視圖中。我有數組加載好,只是不知道如何,從句法上,如何獲得數組中的當前位置。我意識到這是一個總共n00b的問題,所以免費爲您提供聲譽。如何在NSArray中獲取當前位置Objective-C

繼承人一些代碼:

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    imageArray = [NSArray arrayWithObjects:[UIImage imageNamed:@"1.jpg"],[UIImage imageNamed:@"2.jpg"], nil]; 
    imageView.image = [imageArray objectAtIndex:0]; 

} 

- (IBAction)swipeRightGesture:(id)sender { 
imageView.image = [imageArray somethingsomething];//load next object in array 
} 

回答

1
- (IBAction)swipeRightGesture:(id)sender 
{ 
    NSUInteger index = [imageArray indexOfObject:imageView.image] + 1; 

    // do something here to make sure it's not out of bounds 
    // 

    imageView.image = [imageArray objectAtIndex:index];//load next object in array 
} 
+0

注意,作爲indexOfObject:返回最低索引,其相應的陣列圖像是等於imageView.image,這個解決方案需要在陣列中的所有圖像是唯一的。 – magma 2012-01-27 03:08:29

+0

我只是假設所有圖像都是唯一的,否則,爲什麼同一個對象的兩個指針存儲在數組中。 – 2012-01-27 03:10:21

3

數組沒有當前位置。它們不像流,它們只是容器。

因此,有兩種方法來解決這個問題:

  1. 保持單獨的陣列位置,作爲NSInteger在您的視圖控制器實例。根據需要遞增和遞減。使用objectAtIndex在那裏獲取對象。
  2. 使用indexOfObject查找當前圖像的位置。按需要遞增和遞減。使用objectAtIndex在那裏獲取對象。

我推薦第一種方法。

1

該解決方案如下。

-(void)next 
{ 
    if (currentIndex < (count - 1)) 
    { 
     currentIndex ++; 
     NSLog(@"current index : %d", currentIndex); 
    } 
} 

-(void) previous 
{ 
    if (currentIndex > 1) { 
     currentIndex --; 
     [self.commsLayer performOperation:currentIndex]; 
     NSLog(@"current index : %d", currentIndex); 
    }else 
    { 
     if (currentIndex == 1) { 
      currentIndex --; 
      NSLog(@"first current index : %d", currentIndex); 
     } 
    } 
}