How to get a selected item in collection view using indexPathsForSelectedItems

48,620

Solution 1

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

Solution 2

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).

Solution 3

In swift 3:

let index = self.collectionView.indexPathsForSelectedItems?.first

Solution 4

Swift 3.0

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == “segueID”{
        if let destination = segue.destination as? YourDestinationViewController{
            let cell = sender as! UICollectionViewCell
            let indexPath = myCollectionView.indexPath(for: cell)
            let selectedData = myArray[(indexPath?.row)!]

            // postedData is the variable that will be sent, make sure to declare it in YourDestinationViewController
            destination.postedData = selectedData
        }
    }
}
Share:
48,620
jmcastel
Author by

jmcastel

Updated on July 09, 2022

Comments

  • jmcastel
    jmcastel almost 2 years

    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
    
        }
    } 
    
  • jmcastel
    jmcastel over 9 years
    i have got an error with let indexPaths : NSArray = self.collectionView.indexPathsForSelectedItems() telling me that UICollectionViewCell' does not have a member named 'indexPathsForSelectedItems'
  • pbasdf
    pbasdf over 9 years
    UICollectionViewCell? Surely self.collectionView is a UICollectionView?
  • jmcastel
    jmcastel over 9 years
    yes sure.My collectionView is set up with a UICollectionViewController and a custom cell in a UICollectionViewCell
  • pbasdf
    pbasdf over 9 years
    Sorry, just to double check - your self.collectionView is actually a UICollectionViewCell (or a subclass thereof)?
  • jmcastel
    jmcastel over 9 years
    My collectionView is : Optional(<UICollectionView: 0x7fe76507ba00; frame = (0 0; 320 568); clipsToBounds = YES; autoresize = W+H; gestureRecognizers = <NSArray: 0x7fe7633aa320>; layer = <CALayer: 0x7fe7633a9540>; contentOffset: {0, 0}; contentSize: {320, 0}> collection view layout: <UICollectionViewFlowLayout: 0x7fe76339b160>)
  • pbasdf
    pbasdf over 9 years
    So your collectionView is a UICollectionView, so why the error saying UICollectionViewCell does not have a member...? You haven't cast it as UITableViewCell somewhere by mistake?
  • jmcastel
    jmcastel over 9 years
    No :( and it was the reason of my post
  • pbasdf
    pbasdf over 9 years
    I'm not au fait with Swift, but I think that maybe a ! or ? will help. I'll edit my answer...
  • jmcastel
    jmcastel over 9 years
    my zoomVc.post still nil. It seems that the cell is not detected as the sender. Do i have to set something in the storyboard ? I just ctrl drag from the cell to the zoomVc to create a "goToZoom" segue. See my edited post
  • rdelmar
    rdelmar over 9 years
    @jmcastel -- "It seems that the cell..."? Did you actually log cell to see if it's nil or not; it shouldn't be if you made the segue from the cell. Where is zoomVC.post nil (where did you check it)? Is userPost nil in prepareForSegue? You need to do some troubleshooting to see where the problem lies.
  • jmcastel
    jmcastel over 9 years
    astonishment i can't println my cell in the prepareForSegue method. zoomVC.post is nil in viewDidLoad.
  • rdelmar
    rdelmar over 9 years
    What do you mean by, "can't println my cell"? Do you mean it prints as nil?
  • rdelmar
    rdelmar over 9 years
    That's because the if statement is never entered (I had a typo there). It should be "if segue.identifier == "showZoomController" (or whatever your identifier is)
  • Adam
    Adam almost 9 years
    If you don't connect the segue to the cell, but just the controller you will need to use @pbasdf 's solution