简体   繁体   中英

Set selected color of cell in UiCollectionView in 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.

在此处输入图像描述

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

在此处输入图像描述

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
        }

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
}

call selectItemAtIndexPath:animated:scrollPosition: method after reloadData method of UICollectionView

eg

let collectionView = UICollectionView()
collectionView.reloadData()     
collectionView.selectItemAtIndexPath(NSIndexPath(forItem: 0, inSection: 0), animated: true, scrollPosition: .None)

Per to @pedroun's answer, here is my updated answer to make your first cell's default color. Hope this helps you.

@IBOutlet weak var cellImageview: UIImageView!

var cellIndex: Int? {
    didSet {
        guard let index = cellIndex else { return }
        if index != 0 {
            contentView.backgroundColor = UIColor.blueColor()//change this to your unselected cell color.
        }else{
            contentView.backgroundColor = UIColor.redColor()//this is default color for your first cell.
            cellImageview.alpha = 1.0
        }
    }
}

override var selected: Bool {
    didSet {
        contentView.backgroundColor = selected ? UIColor.redColor(): UIColor.blueColor()//change colors as per your requirements
        cellImageview.alpha = selected ? 0.75 : 1.0
    }
}

For the cellIndex property, you need to set it in your cellForRowAtIndexPath as cell.cellIndex = indexPath.row

There is two delegate method in UICollectionViewDelegate.

didDeselectItemAtIndexPath & didSelectItemAtIndexPath

when you click collection cell, you can get indexPath of the cell. And you can get collection cell by using cellForItemAtIndexPath

I have experienced in UITableView and I think UICollectionView is same with following logic.

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    if indexPath.row < arrData.count && arrData.count > 0{
        if let selectedCell = tableView.cellForRowAtIndexPath(indexPath) as? GARatesCell {
        selectedCell.viewBG.backgroundColor = COLOR_NAV_BAR
        selectedCell.lblTitle.textColor = UIColor.whiteColor()
        btnShare.backgroundColor = COLOR_NAV_BAR
        self.selectedIndex = indexPath.row
        }
    }
}

func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {

    if  indexPath.row < arrData.count && arrData.count > 0{
        let deselectedCell = tableView.cellForRowAtIndexPath(indexPath) as? GARatesCell
        if deselectedCell != nil {
            deselectedCell?.viewBG.backgroundColor =  COLOR_BG_BAR
            deselectedCell?.lblTitle.textColor = COLOR_NAV_BAR
        }
    }

}

I know this is not a perfect solution. But it's works.

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    collectionView.visibleCells.forEach {
        $0.backgroundColor = .white
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM