Changing cell background color in UICollectionView in Swift

前端 未结 3 1009
执笔经年
执笔经年 2020-12-09 11:48

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 ch

3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-09 12:16

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

    This creates a constant for the selected UICollectionViewCell, then you just change the background's color


    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!


    For example here is the screenshot from this code in a filterApp

    UICollectionView example

提交回复
热议问题