Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Mohamed Ibrahim
1,086 PointsIndexPath for collectionView
how do I get the index path for a collectionView?
similar to this var indexPath : NSIndexPath = self.tableView.indexPathForSelectedRow!
4 Answers
Steven Deutsch
21,046 PointsHey Mohamed Ibrahim,
indexPathForCell(cell: _ ) is a method that takes a cell as its argument. This means to retrieve the indexPath, you need to pass in the cell that you want this indexPath for. A use case for this would be when you are doing a segue from a collection view cell to another view controller.
In prepare for segue, there is a sender argument that is passed in when it is called. This is the object that triggered the segue, or in this case, lets say your collection view cell.
What you can do is typecast the sender as a UICollectionViewCell, so that you can use the indexPathForCell() method on it.
if let sender = sender as? UICollectionViewCell {
let indexPath = self.collectionView.indexPathForCell(sender)
// Whatever else you want to do
}
Good Luck
Steven Deutsch
21,046 PointsHey Mohamed Ibrahim,
You can use the indexPathForCell() method of UICollectionView. It takes a UICollectionViewCell as its argument.
Good Luck
Mohamed Ibrahim
1,086 Pointsthis is what I tried var indexPath : NSIndexPath = self.collectionView.indexPathforCell! But it doesn't work :p I know I'm such a beginner buying you can type it out it would be nice. Thanks anyways
Mohamed Ibrahim
1,086 PointsBut if *
Mohamed Ibrahim
1,086 Pointsoverride func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let sender = InventionsCollectionViewCell() as? UICollectionViewCell{ let indexPath = inventionCollectionView.indexPathForCell(sender)
if segue.identifier == "showInvention" {
let destViewController = segue.destinationViewController as! inventionsDetailViewController
destViewController.list = inventionsList(index: indexPath!.item)
}
}
}
is this correct?
Mohamed Ibrahim
1,086 Pointsits says that indexPath is nil, and that it is bad instruction
Mohamed Ibrahim
1,086 PointsMohamed Ibrahim
1,086 PointsI figured it out thanks :)