我有一个UICollectionView
我在哪里使用函数 didSelectItemAtIndexPath
选择一个单元格并更改其 alpha。
在 UICollectionView
有12个单元格。
为了将取消选择的单元格带回到 alpha = 1.0
我使用函数didDeselectItemAtIndexPath
.
到目前为止,当我选择一个单元格并滚动 UICollectionView
时,代码可以正常工作。应用程序上线时崩溃let colorCell : UICollectionViewCell = collectionView.cellForItemAtIndexPath(indexPath)!
在取消选择函数内出现错误:
fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)
我想我需要重新加载 Collection View ,但是如何重新加载并保持单元格处于选中状态?
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let colorCell : UICollectionViewCell = collectionView.cellForItemAtIndexPath(indexPath)!
colorCell.alpha = 0.4
}
override func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
let colorCell : UICollectionViewCell = collectionView.cellForItemAtIndexPath(indexPath)!
colorCell.alpha = 1.0
}
最佳答案
发生崩溃的原因是您选择并滚动到屏幕可见区域之外的单元格已被 Collection View 中的其他单元格重复使用。现在,当您尝试使用 cellForItemAtIndexPath
获取 didDeselectItemAtIndexPath
中选定的单元格时,会导致崩溃。
为了避免崩溃,正如 @Michael Dautermann 提到的,使用可选绑定(bind)来验证单元格是否为零,然后设置 alpha
func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
if let cell = collectionView.cellForItemAtIndexPath(indexPath) {
cell.alpha = 1.0
}
}
为了在滚动过程中保持选择状态,请在 cellForItemAtIndexPath
方法中使单元格出队时检查单元格的选择状态并相应地设置 alpha
值
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath)
if cell.selected {
cell.alpha = 0.4
}
else {
cell.alpha = 1.0
}
return cell
}
关于ios - Swift 2 - 调用 `didDeselectItemAtIndexPath` 时出现 fatal error ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33962068/