2016-08-13 2 views
0

UICollectionView에서 탭한 셀의 indexPath를 다른 뷰 컨트롤러로 전달하려고합니다.CollectionViewCell에서 다른 뷰 컨트롤러로 Seague 전달 IndexPath

보기 컨트롤러 "PostCell에 형 포스트의 캐스팅 할 수 없습니다 값": 내가 선택한 일의 indexPath를 얻을

나는이 오류가 다음 뷰 컨트롤러에 SEGUE 수없는 것 # 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

.

나는 인덱스 경로

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을 전달하고 PostCellsender이 아닙니다. collectionView가 선택된 항목을 추적하므로 어쨌든 필요하지 않습니다.

이 시도 : 당신은 예상 PostCell 인스턴스와 일치하지 않는 Post 인스턴스를 전달하는

if let selectedIndex = self.collection.indexPathsForSelectedItems()?.first { 
    print(selectedIndex) 
} 
관련 문제