从CollectionViewCell发送到另一个视图控制器传递IndexPath

时间:2016-08-13 18:04:12

标签: ios swift uicollectionview

我正在尝试将在UICollectionView中轻敲的单元格的indexPath传递给另一个视图控制器。我似乎无法获得所选内容的indexPath并将其转换为下一个视图控制器

我收到此错误:“无法将Post类型的值转换为PostCell”

查看控制器#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
            }

        }

    }
}

查看控制器#2:

var indexNum: NSIndexPath!

override func viewDidLoad() {
    super.viewDidLoad()

   print(indexNum)
}

3 个答案:

答案 0 :(得分:3)

您传递的Post实例与预期的PostCell实例不匹配。

我建议传递索引路径

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

答案 1 :(得分:1)

您正在传递Post而不是PostCell作为sender。无论如何,您都不需要它,因为collectionView会跟踪所选项目。

试试这个:

if let selectedIndex = self.collection.indexPathsForSelectedItems()?.first {
    print(selectedIndex)
}

答案 2 :(得分:0)

这是因为您正在提供类型为Post的参数,并且您尝试将其转换为PostCell。哪个不行。