2015-09-06 61 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

相关问题