在Swift中更改UICollectionView中的单元格背景颜色

问题描述 投票:10回答:3

我正在使用水平集合视图来滚动日期。集合视图包含30个单元格。如果我选择第一个单元格来指示选择,则单元格背景颜色已从默认颜色红色变为棕色。然后,如果我选择另一个单元格,则选定的单元格颜色从红色变为棕色。但是第一个细胞BGColor保持不变(棕色)。如何通过单击其他单元格更改为默认颜色?

       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()
        }

    }
swift ios8 uicollectionview
3个回答
17
投票

您可以将函数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创建一个常量,然后您只需更改背景的颜色


然后,为了在取消选择时返回原始颜色,必须使用带有参数collectionView的函数didDeselectItemAtIndexPath

func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
        let cellToDeselect:UICollectionViewCell = myCollectionView.cellForItemAtIndexPath(indexPath)!
        cellToDeselect.contentView.backgroundColor = UIColor.clearColor()
}

并将颜色更改为原始颜色!


例如,这里是filterApp中此代码的屏幕截图

UICollectionView example


7
投票
var selectedIndex = Int ()

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell

    if selectedIndex == indexPath.row
    {
        cell.backgroundColor = UIColor.green
    }
    else
    {
        cell.backgroundColor = UIColor.red
    }

    return cell
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
{
    selectedIndex = indexPath.row

    self.yourCollctionView.reloadData()
}

可能很疯狂,但它对我来说很好......!


2
投票

您可以维护最后选择的索引路径的副本,然后在didSelectItemAtIndexPath中比较索引路径以查看它们是否不同。如果不同,请根据需要更改这些索引路径上的两个单元格的颜色,然后将旧索引路径复制到旧索引路径上。


编辑

再考虑一下,这应该通过细胞的backgroundViewselectedBackgroundView属性来完成。将单元格出列后,您可以执行以下操作以让iOS处理更改。

cell.backgroundView.backgroundColor = [UIColor redColor];
cell.selectedBackgroundView.backgroundColor = [UIColor brownColor];
© www.soinside.com 2019 - 2024. All rights reserved.