2012-01-27 17 views
2

iOSコーディングが新しくなりました。私はUIImageViewをイメージオブジェクトの配列でロードして実装しようとしています。右のスワイプでは、配列内の次のオブジェクトに移動し、ビューにロードします。私は配列が正常にロードされている、ちょうど、どのように構文的に、配列の現在の位置を取得するか分からない。私はこれが完全にn00bの質問であることを理解しているので、あなたのために自由な評判が得られます。目的地CでNSArrayの現在の位置を取得する方法

HERESにいくつかのコード:

- (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

+0

私はすべての画像が一意であると仮定しました。そうでなければ、配列に同じオブジェクトの2つのポインタが格納されています。 –

3

配列は、現在の位置を持っていません。彼らは川のようなものではなく、ただの容器です。

ので、これを修正するには、2つの方法があります:

  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); 
     } 
    } 
} 
関連する問題