Sam Spencer
Sam Spencer

Reputation: 8609

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

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!

Upvotes: 5

Views: 5503

Answers (2)

zjames
zjames

Reputation: 779

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.

Upvotes: 30

brainondev
brainondev

Reputation: 1117

The delegate method you are using always provides the index path of the cell that was selected. Try to debug with a breakpoint on your NSLog call. When debugger stops on it look at the Debug Area at the bottom and use the console (View => Debug Area => Activate Console if you need it).

Type in the console: po indexPath

You should see something like this if selected item is the 5th of the list in section:0 (first section and probably the only one)

<NSIndexPath 0xa8a6050> 2 indexes [0, 5]

Hope this helps to figure out what's going on.

Upvotes: 1

Related Questions