在Xcode项目中使用未解析的标识符'cell'

时间:2019-06-04 21:28:14

标签: ios swift xcode uicollectionview uicollectionviewcell

在我的匹配应用程序Xcode项目中,我指出了一个错误:

  

使用未解析的标识符“ cell”。

我的代码:

import UIKit

class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    }


    @IBOutlet weak var collectionView: UICollectionView!

    var model = CardModel()
    var cardArray:[Card] = []

    override func viewDidLoad() {
        super.viewDidLoad()

        //call the getCards method of the card model
        cardArray = model.getCards()

        collectionView.delegate = self
        collectionView.dataSource = self

    }

    //mark: -UICollectionView Protocol Methods
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {


        return cardArray.count
    }

     func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {

        //get a cardCollectionViewcell object
        let cell =
            collectionView.dequeueReusableCell(withReuseIdentifier: "CardCell", for: indexPath) as! CardCollectionViewCell

        //get card that
        let card = cardArray[indexPath.row]

        cell.setCard(card)

        return
  }

     func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        _ = collectionView.cellForItem(at: indexPath) as!CardCollectionViewCell

        //flip the card
        cell.flip() <--------- THIS IS THE ERROR

错误修复后,我应该能够在假iPhone上运行比赛应用示例。允许我点击一下翻转卡片。

2 个答案:

答案 0 :(得分:0)

我认为您忘记设置可重复使用的标识符

Storyboard set cell identifier

我希望这能解决您的问题。

要访问该单元格方法,必须声明变量  让cell = collectionView.cellForItem(at:indexPath)as!CardCollectionViewCell

答案 1 :(得分:0)

首先,您滥用collectionView:willDisplay:forItemAt。将所有内容移至collectionView:cellForItemAt,将return替换为return cell,然后删除willDisplay:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell =  collectionView.dequeueReusableCell(withReuseIdentifier: "CardCell", for: indexPath) as! CardCollectionViewCell

    //get card that
    let card = cardArray[indexPath.row]
    cell.setCard(card)
    return cell
}

   func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { ... }

错误非常明显:您从未声明celldidSelectItemAt的范围。更改

let cell = collectionView.cellForItem(at: indexPath) as! CardCollectionViewCell