0

I have a UICollectionView with some cells.

I made some test here:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{

    UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];

    NSLog(@"nsindex path %@", indexPath);

    cell.backgroundColor=[UIColor greenColor];
    return cell;
}

Here is an example of one cell as it appears in the log:

nsindex path <NSIndexPath: 0xc000000000200016> {length = 2, path = 0 - 1}

How would I extract the value 1 (from path = 0 - 1) from the object in this example?

Cory Klein
  • 51,188
  • 43
  • 183
  • 243
Kokodelo
  • 416
  • 1
  • 5
  • 25

3 Answers3

1

you need to do indexPath.row to access the table cell number and indexPath.item to access the collection cell number.

The answer best explained in here:

Community
  • 1
  • 1
Teja Nandamuri
  • 11,045
  • 6
  • 57
  • 109
  • The first sentence of this answer is incorrect. Since this question is about a `UICollectionView`, the correct answer is to use `indexPath.item`, not `indexPath.row`. – rmaddy May 03 '16 at 15:31
0

indexPath.item(available in iOS 6.0 and later) indexPath.row(available in iOS 2.0 and later).

indexPath.item or indexPath.row use this for UICollectionView to get cell number

indexPath.row use this for UITableView to get cell number.
Shashi3456643
  • 2,021
  • 17
  • 21
  • You're not @Teja Nandamuri but you're right to! Thanks! But what is the best one to use? – Kokodelo May 03 '16 at 15:22
  • I've seen in the NSindexPath doc that they are exactly the same, but NSindexpath doesn't have at the beginning the .row – Kokodelo May 03 '16 at 15:26
  • Your recommendation is a bad one. When working with a table view, use `indexPath.row`. When working with a collection view, use `indexPath.item`. Do not just use `indexPath.row` for both. `UICollectionView` specifically adds the `item` property to `NSIndexPath`. Just because `item` and `row` seem to be similar doesn't mean you should use when in place of the other. The implementation of either could change in the future and using the wrong one could suddenly cause a lot of code to start breaking. – rmaddy May 03 '16 at 15:41
  • I agree with indexPath.row used for UITableView my bad I was confused. indexPath.row and indexPath.item used for UICollectionView. I have updated my answer :) – Shashi3456643 May 03 '16 at 15:50
  • Do not use `indexPath.row` for a `UICollectionView`. `UICollectionView` specifically defines the `item` and `section` properties for `NSIndexPath`. – rmaddy May 03 '16 at 15:59
-1

NSIndexPath has two properties: row and section. Property row indicate a number of row in current section.