Reputation: 87
How can I use indexPathForSelectedRow in CollectionView?
CollectionView/TableView:
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("levelCell", forIndexPath: indexPath) as! CollectionViewCell
guard levelListen != nil else {
return cell
}
let levelListe = levelListen[indexPath.row]
cell.levelLabel?.text = levelListe.name
return cell
}
TableView - prepareForSegue (work):
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "zumLevel" {
let dstCtl = segue.destinationViewController as! InLevelViewController
let indexPath = tableView.indexPathForSelectedRow!
dstCtl.levelList = levelListen[indexPath.row]
}
}
CollectionView - prepareForSegue (not work):
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "zumLevel" {
let dstCtl = segue.destinationViewController as! InLevelViewController
// like TableView?
let indexPath = collectionView.indexPathsForSelectedItems()!
dstCtl.levelList = levelListen[indexPath.row] // <--- .row doesn't work, should I use .count ?
}
}
When I try .count it says: "unexpectedly found nil while unwrapping an Optional value"
Upvotes: 1
Views: 509
Reputation: 812
collectionView.indexPathsForSelectedItems()
returns multiple IndexPath's because you can select multiple cells. This function returns an array of IndexPaths, e.g [NSIndexPath].
It should work if you'd do something like:
let indexPath = collectionView.indexPathsForSelectedItems()
if let lastRowSelected = indexPath?.last?.row {
dstCtl.levelList = levelListen[lastRowSelected]
}
Upvotes: 0