在Swift中更改UICollectionView中的单元格背景颜色 [英] Changing cell background color in UICollectionView in Swift

查看:1025
本文介绍了在Swift中更改UICollectionView中的单元格背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用水平集合视图来滚动日期。集合视图包含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

You can use the function collectionView with the parameter 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

UICollectionView示例

这篇关于在Swift中更改UICollectionView中的单元格背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆