gpt4 book ai didi

ios - 触摸时更改 UICollectionViewCell 的颜色

转载 作者:搜寻专家 更新时间:2023-11-01 06:23:37 26 4
gpt4 key购买 nike

我在 Collection View 中有一组单元格,我想让它们像按钮一样工作。

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

我最初可以使用 cellForItemAtIndexPath 方法设置 collectionViewCell 中 view.backgroundColor 的颜色。然而,与我认为这样做会起作用的相反:

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let cell: ButtonCollectionCell = collectionView.dequeueReusableCellWithReuseIdentifier("ButtonCell", forIndexPath: indexPath) as! ButtonCollectionCell
cell.cellBackgroundView.backgroundColor = UIColor.darkGrayColor()
}

颜色还是没变...

本质上,我希望这些单元格的行为与按钮完全一样。我希望它们在我松开手指后在触摸时突出显示为浅灰色(它们最初是白色)我希望它们变成深灰色。

如果我再次触摸,我希望它们再次突出显示为浅灰色,然后再次变为白色。

如果 didSelectItemAtIndexPath 不是这样做的方法,那是什么?

最佳答案

我建议您对代码进行一些更改,以帮助您解决错误。

首先,我会调用 cellForItemAtIndexPath 方法来获取您的 cell,而不是使用 dequeue 方法:

let cell = collectionView.cellForItemAtIndexPath(indexPath) as! ButtonCollectionCell

然后你应该在 didSelectItemAtIndexPath 方法中调用 reloadItemsAtIndexPaths 来重新加载单元格:

collectionView.reloadItemsAtIndexPaths([indexPath])

此外,您不应在 didSelectItemAtIndexPath 方法中更改背景,而应在检查单元格是否被选中的 cellForItemAtIndexPath 方法中更改:

if(cell?.selected){
//set your background-color
}else{
//change color
}

关于ios - 触摸时更改 UICollectionViewCell 的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28613893/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com