Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a selected item in collection view using indexPathsForSelectedItems

I have a collectionView of photos and want to pass the photo who was cliked to a detailViewControler.

The collection data come from :

 var timeLineData:NSMutableArray = NSMutableArray ()

I would like to use the prepare for segue method.

My problem is how to get the good indexPath from the cell who was clicked ?

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue == "goToZoom" {
        let zoomVC : PhotoZoomViewController = segue.destinationViewController as PhotoZoomViewController
        let cell = sender as UserPostsCell

        let indexPath = self.collectionView!.indexPathForCell(cell)
        let userPost  = self.timeLineData.objectAtIndex(indexPath!.row) as PFObject
        zoomVC.post = userPost

    }
} 
like image 326
jmcastel Avatar asked Oct 11 '14 12:10

jmcastel


1 Answers

The sender argument in prepareForSegue:sender: will be the cell if you connected the segue from the cell. In that case you can get the indexPath from the cell,

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "showZoomController" {
       let zoomVC = segue.destinationViewController as PhotoZoomViewController
       let cell = sender as UICollectionViewCell
       let indexPath = self.collectionView!.indexPathForCell(cell)
       let userPost  = self.timeLineData.objectAtIndex(indexPath.row) as PFObject
        zoomVC.post = userPost
    }
} 
like image 62
rdelmar Avatar answered Sep 21 '22 08:09

rdelmar