为什么不能使用列表类型'(UICollectionView)'的参数调用'indexPathForCell'?

时间:2015-09-06 14:28:13

标签: ios swift uicollectionview viewcontroller

我使用此tutorial创建了UICollectionView。 然后我希望从这个UICollectionView传递indexPath到我的GameViewController,就像在这个question/answer中一样。

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。我收到这个错误:

无法使用类型为'(UICollectionViewCell)'的参数列表调用'indexPathForCell'

如何获取我刚刚在UICollectionView中触及的元素的indexPath,以便我可以将其从此函数绕过GameViewController?

1 个答案:

答案 0 :(得分:0)

您将sender转换为UICollectionView,但可能UICollectionViewCell

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