【发布时间】:2016-03-06 23:52:30
【问题描述】:
我有一个包含 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”行。
我不想使用出队单元格的原因是我需要在运行时根据用户选择突出显示一些单元格,如果我使用出队单元格,它似乎不会保留突出显示滚动线下方的那些。
【问题讨论】:
-
原来我的问题与单元格出队无关......这都在 didSelect 和 didDeselectCellAtIndexPath 方法中......但如果我的问题与单元格出队有关,下面的答案会有工作。
标签: ios swift uicollectionview uicollectionviewcell