iOS编码的新手,所以这可能更像是一个语法问题。我正在尝试实现一个加载了图像对象数组的UIImageView。向右滑动时,我想移动到阵列中的下一个对象,并将其加载到视图中。我已经很好地加载了数组,只是不知道如何从语法上获得数组中的当前位置。我知道这是一个完全n00b的问题,所以免费信誉为你。
这里有一些代码:
- (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
}
数组没有当前位置。它们不是流式的,它们只是容器。
所以有两种方法可以解决这个问题:
- 将数组位置单独保留,作为视图控制器实例中的
NSInteger
。根据需要递增和递减。使用objectAtIndex
将对象获取到那里 - 使用
indexOfObject
查找当前图像的位置。根据需要递增和递减。使用objectAtIndex
将对象获取到那里
我推荐第一种方法。
- (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
}
下面给出了解决方案。
-(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);
}
}
}