2016-08-13 105 views
0

我想通过在UICollectionView中点击一个单元格的索引路径到另一个视图控制器。我似乎无法得到选择什么样的indexPath并Segue公司下一个视图控制器Segue从CollectionViewCell另一个视图控制器通过IndexPath

我得到这个错误:

视图控制器“型邮政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

你传递一个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 
    } 
} 
+0

很不错的!我现在一定明白。非常感谢你! – kelsheikh

0

这是因为你正在给出类型为Post的参数,并且您试图将其转换为PostCell。哪个不行。

1

您通过Post而不是PostCell作为sender。无论如何,您并不需要这样做,因为collectionView会跟踪选定的项目。

试试这个:

if let selectedIndex = self.collection.indexPathsForSelectedItems()?.first { 
    print(selectedIndex) 
} 
相关问题