Работая над быстрой отменой очереди ячейки в UICollectionView - получая ошибку в cellForItem, при попытке повторного использования ячейки - PullRequest
0 голосов
/ 04 мая 2018

Работает над быстрой отменой очереди ячейки в 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 голосов
/ 04 мая 2018

Вы должны разыграть ячейку в своей ячейке так:

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
0 голосов
/ 04 мая 2018

Оба значения titleLabel и deviceImageView находятся в 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
}
0 голосов
/ 04 мая 2018

Вы должны разыграть ячейку с as! MyCell, поскольку 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
} 
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...