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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With