J.Doe
J.Doe

Reputation: 11

How to change background color of UIcollectionViewCell on tap using swift?

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath){
        if let cell = collectionView.cellForItem(at: indexPath) {
            cell.backgroundColor = UIColor.green
        }
}

Why it takes about 45 seconds to show background color when I tap on cell? Is there any other way to do that?

Upvotes: 0

Views: 1778

Answers (3)

Frankenxtein
Frankenxtein

Reputation: 493

Do this on your class extending UICollectionViewCell:

override var isSelected: Bool {
        didSet {
            backgroundColor = isSelected ? UIColor.black : UIColor.blue
        }
    }

Upvotes: 2

Jignesh Mayani
Jignesh Mayani

Reputation: 7213

You may use this as well and by this you can do customisation with time

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    if let cell = collectionView.cellForItem(at: indexPath)
    {
           cell.backgroundColor = .green

        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2 , execute:
        {
              cell.backgroundColor = .clear
        })
    }
}

Upvotes: 0

Abdelahad Darwish
Abdelahad Darwish

Reputation: 6067

Just remove this line

 self.collectionView?.reloadData()

To be like that :

  func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if let cell = collectionView.cellForItem(at: indexPath){
            cell.backgroundColor = .green
        }


    }

    func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
        if let cell = collectionView.cellForItem(at: indexPath){
            cell.backgroundColor = .clear
        }
    }

Upvotes: 0

Related Questions