我在集合视图中有一个单元格数组,我希望它像按钮一样。
当我点击一个时,我希望该单元格突出显示,然后更改颜色。
我能够初步设置collectionViewCell里面的view.backgroundColor的颜色cellForItemAtIndexPath
方法。但是,如果我这样做,与我认为的相反:
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let cell: ButtonCollectionCell = collectionView.dequeueReusableCellWithReuseIdentifier("ButtonCell", forIndexPath: indexPath) as! ButtonCollectionCell
cell.cellBackgroundView.backgroundColor = UIColor.darkGrayColor()
}
颜色仍然没有变化......
基本上我希望这些单元格的行为与按钮完全相同。我希望他们在我松开手指后突出显示浅灰色(最初是白色),我希望它们变成深灰色。
如果我再次触摸,我希望它们再次突出显示为浅灰色,然后再次变为白色。
如果didSelectItemAtIndexPath
没有办法,那是什么?
答案 0 :(得分:2)
我建议您对代码进行一些更改,以帮助您解决错误。
首先,我会调用cellForItemAtIndexPath
方法来获取cell
,而不是使用dequeue
方法:
let cell = collectionView.cellForItemAtIndexPath(indexPath) as! ButtonCollectionCell
然后你应该调用reloadItemsAtIndexPaths
方法中的didSelectItemAtIndexPath
来重新加载单元格:
collectionView.reloadItemsAtIndexPaths([indexPath])
此外,您不应该更改didSelectItemAtIndexPath方法中的背景,而是在cellForItemAtIndexPath
方法中检查是否选中了单元格:
if(cell?.selected){
//set your background-color
}else{
//change color
}
答案 1 :(得分:1)
您可以为UICollectionView
实施自己的降落手势识别器。见https://stackoverflow.com/a/15629234/1557276
完成后,请调用-indexPathForItemAtPoint:
实例的UICollectionView
方法,然后在-cellForItemAtIndexPath:
答案 2 :(得分:1)
当您dequeueReusableCellWithReuseIdentifier
时,它可以向您返回一个新单元格。
而是使用cellForItemAtIndexPath
来获取该索引路径的当前单元格。
答案 3 :(得分:0)
将这行代码放在我的方法中:
collectionView.cellForItem(at: indexPath)?.backgroundColor = UIColor.cyan