在UICollectionView中快速出列单元格 - 在cellForItemAt中获取错误尝试重用单元格

时间:2018-05-04 19:10:48

标签: ios swift uicollectionview

在UICollectionView

中快速出列单元格
let cellClass: AnyClass = MyCell.self
var cellIdentifier: String { return String(describing: cellClass) }

override func viewDidLoad() {
    super.viewDidLoad()
    collectionView?.register(MyCell.self, forCellWithReuseIdentifier: cellIdentifier)
}

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath)
    cell.titleLabel.text = cellType.properties.titleText
    cell.deviceImageView.image = cellType.properties.image
    return cell
}

尽量避免将重用的单元格转换为适当的类型。

看到错误:

  

类型的值' UICollectionViewCell'没有会员' titleLabel'
  类型的价值' UICollectionViewCell'没有会员' deviceImageView'

3 个答案:

答案 0 :(得分:1)

您需要使用dequeueReusableCell投放单元格,UICollectionViewCell返回override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! MyCell cell.titleLabel.text = cellType.properties.titleText cell.deviceImageView.image = cellType.properties.image return cell }

cusipObj

答案 1 :(得分:0)

您需要在自定义单元格中投放单元格,如下所示:

guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as? MyCell else {
            fatalError()
        }
cell.titleLabel.text = cellType.properties.titleText
cell.deviceImageView.image = cellType.properties.image

答案 2 :(得分:0)

titleLabeldeviceImageView都位于MyCell,但您默认加载UICollectionViewCell

您需要将collectionCell类型转换为MyCell。如果无法加载guard,请使用MyCell语句:

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as? MyCell else { fatalError("can not load MyCell") }

    cell.titleLabel.text = cellType.properties.titleText
    cell.deviceImageView.image = cellType.properties.image

    return cell
}