【问题标题】:How to get current position in NSArray in objective-C如何在objective-C中获取NSArray中的当前位置
【发布时间】:2012-02-20 02:18:21
【问题描述】:

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
}

【问题讨论】:

    标签: ios uiimageview nsarray


    【解决方案1】:

    数组没有当前位置。它们不是流式的,它们只是容器。

    所以有两种方法可以解决这个问题:

    1. 单独保留您的数组位置,作为视图控制器实例中的NSInteger。根据需要增加和减少它。使用objectAtIndex 将对象放在那里。
    2. 使用indexOfObject 查找当前图像的位置。根据需要增加和减少。使用objectAtIndex 将对象放在那里。

    我推荐第一种方法。

    【讨论】:

      【解决方案2】:
      - (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
      }
      

      【讨论】:

      • 注意,由于indexOfObject:返回对应数组图像等于imageView.image的最低索引,该方案要求数组中的所有图像都是唯一的。
      • 我只是假设所有图像都是唯一的,否则为什么要在数组中存储相同对象的两个指针。
      【解决方案3】:

      解决方法如下。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多