kampbell411 kampbell411 - 3 months ago 17
Swift Question

Segue from CollectionViewCell to Another View Controller Passing IndexPath

I'm trying to pass the indexPath of a cell tapped in a UICollectionView to another view controller. I can't seem to get the indexPath of what was selected and segue it to the next view controller

I get this error: "Could not cast value of type Post to PostCell"

View Controller #1:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let post = posts[indexPath.row]
if let cell = collectionView.dequeueReusableCellWithReuseIdentifier("PostCell", forIndexPath: indexPath) as? PostCell {
cell.configureCell(post)
}
return cell
}
}

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let selectedPost: Post!
selectedPost = posts[indexPath.row]
performSegueWithIdentifier("PostDetailVC", sender: selectedPost)
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "PostDetailVC" {

//Error here: Could not cast value of Post to PostCell
if let selectedIndex = self.collection.indexPathForCell(sender as! PostCell){
print(selectedIndex)
}

if let detailsVC = segue.destinationViewController as? PostDetailVC {
if let selectedPost = sender as? Post {
print(selectedIndex)
detailsVC.post = selectedPost
detailsVC.myId = self.myId!
detailsVC.indexNum = selectedIndex
}

}

}
}


View Controller #2:

var indexNum: NSIndexPath!

override func viewDidLoad() {
super.viewDidLoad()

print(indexNum)
}

Answer

You are passing a Post instance which doesn't match the expected PostCell instance.

I recommend to pass the index path

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    performSegueWithIdentifier("PostDetailVC", sender: indexPath)
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "PostDetailVC" {
       guard let selectedIndexPath = sender as? NSIndexPath,
                 detailsVC = segue.destinationViewController as? PostDetailVC else { return }
       print(selectedIndexPath)

       let selectedPost = posts[selectedIndexPath.row]
       detailsVC.post = selectedPost
       detailsVC.myId = self.myId!
       detailsVC.indexNum = selectedIndexPath
   }
}