Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

indexPath Value of UICollectionView

When using a UICollectionView, I am perplexed with getting the indexPath value of the didSelectItemAtIndexPath method.

I'm using the following line of code in the didSelectItemAtIndexPath method:

//FileList is an NSArray of files from the Documents Folder within my app.
//This line gets the indexPath of the selected item and finds the same index in the Array
NSString *selectedItem = [NSString stringWithFormat:@"%@",[FileList objectAtIndex:indexPath.item]];

//Now the selected file name is displayed using NSLog
NSLog(@"Selected File: %@", selectedItem);

The problem is that the indexPath always returns 0 (see below code) and as a result only the first item in the FileList NSArray is ever selected.

I've tried different parameters such as

  • indexPath.row
  • indexPath.item
  • and just plain indexPath

ALL of these return a value of 0 in the following NSLog statement:

NSLog(@"index path: %d", indexPath.item); //I also tried indexPath.row here

Maybe I'm just formatting the NSString improperly, however I don't think this is the case as there are no warnings and I've tried formatting it differently in other places.

Why does the indexPath always return 0?

Any help would be appreciated! Thanks!

like image 297
Sam Spencer Avatar asked Oct 06 '12 15:10

Sam Spencer


People also ask

What is IndexPath in tableView Swift?

indexPath(for:)Returns an index path that represents the row and section of a specified table-view cell.

What is IndexPath?

A list of indexes that together represent the path to a specific location in a tree of nested arrays.

What is a UICollectionView?

An object that manages an ordered collection of data items and presents them using customizable layouts.


1 Answers

At the risk of stating the obvious, make sure your code is in the didSelectItemAtIndexPath method rather than didDeselectItemAtIndexPath. You will get very different indexPath values for a given touch event in the latter method and it's quite easy to insert the wrong one with Xcode's code completion.

like image 62
zjames Avatar answered Sep 21 '22 00:09

zjames