我在使用 Collection View 中的选定项时遇到问题。
选中的项目将 backgroundColor 更改为蓝色,但似乎可重复使用的单元格也受到了影响。
我的代码是这样的:
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
var cell = collectionView.cellForItemAtIndexPath(indexPath) as UICollectionViewCell?
cell?.contentView.backgroundColor = UIColor.blueColor()
func collectionView(collectionView: UICollectionView, didDeslectItemAtIndexPath indexPath: NSIndexPath) {
var cell = collectionView.cellForItemAtIndexPath(indexPath) as UICollectionViewCell?
cell?.contentView.backgroundColor = UIColor.blackColor()
}
func collectionView(collectionView: UIControllerView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell: boxCell = collectionView.dequeueReusableCellWithReuseIdentifier("demoCell", forIndexPath: indexPath) as boxCell
cell.cellTitle.text = name[indexPath.row]
}
当我运行应用程序时,选择有效,选择另一个单元格,取消选择其他选定的单元格,但是当我滚动时,可重复使用的单元格也变成蓝色。
我使用的是水平滚动方向,每行只有 1 行和 4 个单元格。
我哪里错了?还有其他人遇到过这个问题吗?
最佳答案
这是正常行为 - 原因是项目被重复使用,并且在重复使用后它们会通过 cellForItemAtIndexPath
,您没有设置背景颜色,因此它们会保留您设置的最后一个 - 在你的案例 didSelect 方法。
您应该创建一个 NSSet
,您将在其中保留所有选定的 NSIndexPath
,并在选择/取消选择时向其添加/删除 NSIndexPath
。
设置背景颜色逻辑应该在 cellForItemAtIndexPath
中完成 - 在您检查 NSIndexPath
是否存在于您的 NSSet
中之后,您可以设置所需的颜色。
在选择时,您还必须重新加载特定元素,因此它会为您单击的元素调用 cellForItemAtIndexPath
。
关于ios - Swift - 在 Collection View 中选择项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28783557/