[英]Swift collectionView non reusable cell
我有一个带有2个部分的collectionView,每个部分应基于同一单元格(仅包含UIImageView)。 这些部分之间的唯一区别是它们应包含的单元格数量和显示的图像类型。
如果将cellforItemAtIndexPath方法设置为使用出队的单元格(collectionView.dequeueReusableCellWithIdentifier),则所有填充都很好,如果将其设置为使用自定义单元格的实例而不出队,则会崩溃。
cellForItemAtIndexPath方法:
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
//cannot use dequedReusableCell since some cells below scroll-line should remain highlighted
let cell = NumbersCollectionViewCell() // CAUSES CRASH
// let cell = collectionView.dequeueReusableCellWithReuseIdentifier(Constants.cellIdentifier, forIndexPath: indexPath) as! NumbersCollectionViewCell // WORKS FINE
switch indexPath.section {
case 0: cell.imageView.image = UIImage(named: numberImageFiles[indexPath.row])
case 1: cell.imageView.image = UIImage(named: specialNumberImageFiles[indexPath.row])
default: break
}
return cell
}
NumbersCollectionViewCell定义:
class NumbersCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var imageView: UIImageView!
}
出现的错误是:“致命错误:在展开可选值时意外发现nil”,它突出显示了我的cellForItemAtIndexPath方法中的“ case 0”行。
我不想使用出队单元格的原因是,我需要根据用户的选择在运行时突出显示某些单元格,并且如果我使用出队单元格,似乎并没有将其保持在滚动行突出显示。
假设你有一个既.swift
和.xib
为你的文件,你需要实例化NumbersCollectionViewCell
这样的:例如,
let numbersCollectionViewCell = UINib(nibName: "NumbersCollectionViewCell", bundle: bundle).instantiateWithOwner(nil, options: nil)[0] as! NumbersCollectionViewCell
否则,您的IBOutlet
不会被连接。
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCellWithReuseIdentifier(identifier: "NumbersCollectionViewCell">, forIndexPath: NSIndexPath>) as? NumbersCollectionViewCell else {
print("failed to get cell")
return UICollectionViewCell()
}
switch indexPath.section {
case 0: cell.imageView.image = UIImage(named: numberImageFiles[indexPath.row])
case 1: cell.imageView.image = UIImage(named: specialNumberImageFiles[indexPath.row])
default: break
}
return cell
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.