2012-01-27 24 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); 
     } 
    } 
}