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
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!
indexPath(for:)Returns an index path that represents the row and section of a specified table-view cell.
A list of indexes that together represent the path to a specific location in a tree of nested arrays.
An object that manages an ordered collection of data items and presents them using customizable layouts.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With