在 Swift 中更改 UICollectionView 中的单元格背景颜色 [英] Changing cell background color in UICollectionView in Swift
问题描述
我正在使用水平集合视图来滚动日期.集合视图包含 30 个单元格.如果我选择第一个单元格,以指示选择,单元格背景颜色已从默认颜色红色变为棕色.然后,如果我选择另一个单元格,则选定的单元格颜色已从红色变为棕色.但第一个单元格 BGColor 保持不变(棕色).如何通过单击其他单元格更改为默认颜色?
I am using horizontal collection view to scroll dates. Collection view contain 30 cells. If I select first cell, to indicate the selection, cell background color has been change to brown from default color red. Then, if I select another cell, selected cell color has changed to brown from red. But first cell BGColor remains the same (brown). How can i change to default color by clicking other cell?
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath
indexPath: NSIndexPath) -> UICollectionViewCell {
var cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell",
forIndexPath: indexPath) as myViewCell
cell.date_label.text = arr_date[indexPath.item]
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath
indexPath: NSIndexPath) {
var cell = collectionView.cellForItemAtIndexPath(indexPath) as myViewCell
if(cell.selected)
{
cell.backgroundColor = UIColor.brownColor()
}
else
{
cell.backgroundColor = UIColor.redColor()
}
}
推荐答案
可以使用collectionView
函数,参数didSelectItemAtIndexPath
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath
indexPath: NSIndexPath) {
let selectedCell:UICollectionViewCell = myCollectionView.cellForItemAtIndexPath(indexPath)!
selectedCell.contentView.backgroundColor = UIColor(red: 102/256, green: 255/256, blue: 255/256, alpha: 0.66)
}
这会为选中的UICollectionViewCell
创建一个常量,然后你只需改变背景的颜色
This creates a constant for the selected UICollectionViewCell
, then you just change the background's color
然后要在取消选择时返回原来的颜色,你必须使用函数collectionView
和参数didDeselectItemAtIndexPath
And then for return to the original color when it is deselected, you must use the function collectionView
with the parameter didDeselectItemAtIndexPath
func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
let cellToDeselect:UICollectionViewCell = myCollectionView.cellForItemAtIndexPath(indexPath)!
cellToDeselect.contentView.backgroundColor = UIColor.clearColor()
}
然后你把颜色改成原来的!
And you change the color to the original one!
例如,这里是此代码在 filterApp 中的屏幕截图
For example here is the screenshot from this code in a filterApp
这篇关于在 Swift 中更改 UICollectionView 中的单元格背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!