2015-09-06 24 views
0

我用這個tutorial創建了一個UICollectionView。 然後我想從這個UICollectionView傳遞indexPath到我的GameViewController,就像這個question/answer一樣。爲什麼不能用列表類型'(UICollectionView)'的參數調用'indexPathForCell'?

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { 
    let cell: LevelCell = collectionView.dequeueReusableCellWithReuseIdentifier("Level", forIndexPath: indexPath) as! LevelCell 
    cell.imgCell.image = UIImage(named: levels[indexPath.row + 1]!.levelImage) 
    cell.lblCell.text = levels[indexPath.row + 1]!.levelLabel 
    return cell 
} 

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { 
    if segue.identifier == "StartGame" { 
     if let gameView = segue.destinationViewController as? GameViewController { 
      if let cell = sender as? UICollectionViewCell, indexPath = collectionView.indexPathForCell(cell) { 
       gameView.level = indexPath 
      } 
     } 
    } 
} 

但是,這並不正常工作 - 甚至當我使用LevelCell代替UICollectionViewCell。我得到這個錯誤:

不能援引「indexPathForCell」有型「(UICollectionViewCell)」參數列表

我怎樣才能得到我只是摸了摸我的UICollectionView元素的indexPath讓我能旁路它從這個函數到GameViewController?

回答

0

您正在將sender轉換爲UICollectionView,但它可能是UICollectionViewCell

if let cell = sender as? UICollectionViewCell, indexPath = collectionView.indexPathForCell(cell) { 
    gameView.level = indexPath 
} 
+0

我更新了我的問題。我正在使用'UICollectionViewCell'或'LevelCell',這也是一個單元格。但我仍然得到這個錯誤,不知道爲什麼。 – Jurik

+0

錯誤必須在其他地方。 – Jurik

+0

我必須是類型轉換或可選/非可選問題。 'collectionView'是一個未包裝的可選實例變量嗎? – vadian

相關問題