Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set selected color of cell in UiCollectionView in swift

Tags:

ios

swift

I am using collectionview to display data.

each cell's selected and unselected color is there

but i want to set default color of first cell in collectionview.

enter image description here

if there are 10 data. my first cell should be like in screenshot

how to achieve this? when i set color at indexpath this issue occurs

enter image description here

like image 280
Krutarth Patel Avatar asked Sep 02 '16 13:09

Krutarth Patel


2 Answers

For two different colors based on selected state of the cell, you may need to subclass your UICollectionViewCell like this:

import UIKit 

class YourCollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var imageView: UIImageView! // for example - some UI element inside cell ...

    override var isSelected: Bool {
        didSet {
            self.contentView.backgroundColor = isSelected ? UIColor.blue : UIColor.yellow
            self.imageView.alpha = isSelected ? 0.75 : 1.0
        }  
      }
    }


// and below you will have your original code

class YourViewController: UICollectionViewController {

... etc

Answering your question - for exceptional style of the first cell:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell ... 

        if(indexPath.row == 0) { //for first cell in the collection
            cell.backgroundColor = UIColor.orange
        } else {
            cell.backgroundColor = UIColor.green
        }
like image 58
pedrouan Avatar answered Oct 14 '22 03:10

pedrouan


this is my code for this issue. Hope it save time for you :)

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "customCell", for: indexPath) as! CustomCell
    
    if let indexPaths = collectionView.indexPathsForSelectedItems, let indexP = indexPaths.first {
        cell.bgView.backgroundColor = indexP == indexPath ? .white : .lightGray
    }
    
    return cell
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    if let cell = collectionView.cellForItem(at: indexPath) as? CustomCell {
        cell.bgView.backgroundColor = .white 
    }
}

func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
    guard let cell = collectionView.cellForItem(at: indexPath) as? CustomCell else {
        return
    }
    
    cell.bgView.backgroundColor = .lightGray
}
like image 32
logan.Nguyen Avatar answered Oct 14 '22 04:10

logan.Nguyen