Jerrod
Jerrod

Reputation: 183

Sending information to detail view upon CollectionViewCell selection

I'm trying to send information to a detail view about the cell selected upon selection. Right now, prepareForSegue runs prior to the collection view delegate method I'm using. This results in me sending the information of the previous cell selection and not the current one.

    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    collectionView.deselectItemAtIndexPath(indexPath, animated: true)        
    nextScreenRow = indexPath.row

    self.performSegueWithIdentifier("toDetails", sender: self)
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
    if segue.identifier == "toDetails" {
        let vc = segue.destinationViewController as HistoryDetailsViewController
        vc.postcard = postcards[nextScreenRow]
    }
}

Upvotes: 1

Views: 65

Answers (1)

rdelmar
rdelmar

Reputation: 104082

Two things. If the segue is made from the cell, then you shouldn't be calling performSegue in code; selecting the cell will trigger the segue with no code. Secondly, when you connect a segue this way, you don't need to implement didSelectItemAtIndexPath at all (but it's ok if you just want to call deselectItemAtIndexPath). There's no need for it; you can do everything you need to in prepareForSegue. The cell will be the sender, so can just do this,

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
    if segue.identifier == "toDetails" {
        let cell = sender as UICollectionViewCell
        let indexPath = collectionView!.indexPathForCell(cell)
        let vc = segue.destinationViewController as HistoryDetailsViewController
        vc.postcard = postcards[indexPath.item]
    }
}

Upvotes: 1

Related Questions