How to get a selected item in collection view using indexPathsForSelectedItems How to get a selected item in collection view using indexPathsForSelectedItems ios ios

How to get a selected item in collection view using indexPathsForSelectedItems


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    }} 


The indexPathsForSelectedItems returns an array of indexPaths (since there might be several items selected) so you need to use:

let indexPaths : NSArray = self.collectionView!.indexPathsForSelectedItems()let indexPath : NSIndexPath = indexPaths[0] as NSIndexPath

(You should probably test to see whether several items are selected, and handle accordingly).


In swift 3:

let index = self.collectionView.indexPathsForSelectedItems?.first