Ios 正在处理UICollectionView中某个单元格的快速出列-尝试重用该单元格时CellForItem中出现错误
正在处理UICollectionView中单元格的快速出列Ios 正在处理UICollectionView中某个单元格的快速出列-尝试重用该单元格时CellForItem中出现错误,ios,swift,uicollectionview,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, forCellWithReuseI
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”
您必须使用
将单元格强制转换为!MyCell
asdequeueReusableCell
返回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
}
您需要在自定义单元格中强制转换单元格,如下所示:
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
titleLabel
和deviceImageView
都位于MyCell
中,但默认情况下您正在加载UICollectionViewCell
您需要将collectionCell类型强制转换为MyCell
。如果无法加载MyCell,请使用guard
语句:
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
}
没有必要为此使用
防护装置。简单地强制释放细胞。如果你的应用程序设置不正确,它将崩溃(这是你希望发生的),你可以修复错误。没有必要为此使用guard。简单地强制释放细胞。如果你的应用程序设置不正确,它将崩溃(这是你希望发生的),你可以修复错误。事实上,使用guard
和fatalError
在很大程度上是毫无意义的<代码>防护
应在适当的情况下用于防止崩溃。感谢@rmaddy,我们通常使用它来调试开发类型的错误。为什么要尝试避免强制转换?你无法避免。避免它是你问题的原因。