Muju
Muju

Reputation: 979

how to change cell background colour on selected item in UICollectionView and change other Cell colour to default in swift

I am new in swift and I am trying to change cell background colour of UICollectionView but its not working my code is like this in cellForItemAt

if(cell.isSelected){
    cell.backgroundColor = UIColor.green
    }else{
       cell.backgroundColor = UIColor.clear
 }

Is there is any way to change only selected cell colour to green and other cell to clear Thanks in Advance!

Upvotes: 1

Views: 2499

Answers (3)

AzeTech
AzeTech

Reputation: 707

Set Selected in your collection cell....

class CollectionCell: UICollectionViewCell {
        
        @IBOutlet weak var imageView: UIImageView!
        @IBOutlet weak var tagTitle: UILabel!
        
        override var isSelected: Bool {
            didSet {
                contentView.backgroundColor = isSelected ? .red : .white
            }
        }
        
        override func awakeFromNib() {
            super.awakeFromNib()
            
        }
    }

Upvotes: 0

Matan
Matan

Reputation: 1003

According to Apple's explanation about cell's backgroungView and selected backgroundView Here you should change those parameters at the cell class itself and the UICollectionView will know to manage it automatically when the cell is highlighted or selected:

override func awakeFromNib() {
  super.awakeFromNib()

  let redView = UIView(frame: bounds)
  redView.backgroundColor = #colorLiteral(red: 1, green: 0, blue: 0, alpha: 1)
  self.backgroundView = redView

  let blueView = UIView(frame: bounds)
  blueView.backgroundColor = #colorLiteral(red: 0, green: 0, blue: 1, alpha: 1)
  self.selectedBackgroundView = blueView
}

Upvotes: 1

Shehata Gamal
Shehata Gamal

Reputation: 100543

Create a variable inside the vc

var currentSelected:Int?

then inside cellForItemAt

cell.backgroundColor = currentSelected == indexPath.row ? UIColor.green : UIColor.clear

finally didSelectItemAt

currentSelected = indexPath.row
collectionView.reloadData()

Don't depend on isSelected as cells are dequeued and when you scroll you'll get unexpected results

Upvotes: 6

Related Questions