在触摸时更改UICollectionViewCell的颜色

时间:2015-02-19 18:16:43

标签: ios swift uicollectionview uicollectionviewcell

我在集合视图中有一个单元格数组,我希望它像按钮一样。

当我点击一个时,我希望该单元格突出显示,然后更改颜色。

我能够初步设置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没有办法,那是什么?

4 个答案:

答案 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