Changing cell background color in UICollectionView in Swift

前端 未结 3 1010
执笔经年
执笔经年 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

    0 讨论(0)
  • 2020-12-09 12:16
    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()
    }
    

    May be crazy, But it works fine for me...!

    0 讨论(0)
  • 2020-12-09 12:33

    You could maintain a copy of the last selected index path, and then in your didSelectItemAtIndexPath compare the index paths to see if they are different. If different, change the colors of the two cells at those index paths as necessary and then copy the new index path over the old.


    Edit

    Thinking about this again, this should be done with the backgroundView and selectedBackgroundView properties of the cells. After you dequeue a cell you can do the following to let iOS handle the changing.

    cell.backgroundView.backgroundColor = [UIColor redColor];
    cell.selectedBackgroundView.backgroundColor = [UIColor brownColor];
    
    0 讨论(0)
提交回复
热议问题