Вопрос

I have got the NSIndexPath from a uitableview before but I'm not sure why this doesn't work for collectionview? Any help would be greatly appreciated!

Here's the code I need to fix:

NSIndexPath *indexPath = [self.collectionView indexPathForSelectedRow];
sqlColumns *author = [self.favoriteExercises objectAtIndex:indexPath.row];
Это было полезно?

Решение

Just use indexPathsForSelectedItems in place of indexPathsForSelectedRow. But this instruction will return more than one indexPath if you select more than one item. You should restrict the selection to one item by setting the allowsMultipleSelection of the UICollectionView to NO.

That said, Xcode has a brilliant autocompletion feature, you could have started to type "index" and it would have shown indexPathsForSelectedItems directly, you can also refer to the excellent documentation provided with Xcode. I Hope it will help you!

UPDATE 1 - How to grab the indexPath from the array

the indexPathsForSelectedItems method will return an array of NSIndexPath objects, each of which corresponds to a single selected item. If there are no selected items, this method returns an empty array.

Now to access this object, you have to ask yourself, how do I access an array? You do some research and then you will come to this conclusion:

NSArray *arrayOfIndexPaths = [self.collectionView indexPathsForSelectedItems];
NSIndexPath *indexPathImInterestedIn = [arrayOfIndexPaths firstObject];

//Voila

Другие советы

There is no method indexPathForSelectedRow: in collection views because collection views are not limited to rows. You can have rows, columns, circles, spirals, rows AND columns, or an almost limitless list of different ways to arrange cells.

Do a search in the UICollectionView class reference for methods who's names begin with "indexPath".

The closest match is probably:

indexPathsForSelectedItems:

That method works for single or multiple selections. It returns an array of indexPaths instead of a single indexPath (much like the table view method indexPathsForSelectedRows for table views that support multiple selections).

There are also methods indexPathForCell:, indexPathForItemAtPoint:, and indexPathsForVisibleItems.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top