Krutarth Patel Krutarth Patel - 1 month ago 4x
Swift Question

in Collectionview how to set colors according to selection?

My requirement is to set by default color at first

and I want to change colors according to selection.

My Requirement is when collectionview will load at first index background color should be Red Color.and deselected color is blue color.
how to manage this
Here is my code

import UIKit
class MyCollectionViewCell: UICollectionViewCell {
override var selected: Bool {
didSet {
contentView.backgroundColor = selected ? UIColor.redColor(): UIColor.blueColor()

class ViewController: UIViewController {
@IBOutlet var collView: UICollectionView!

override func viewDidLoad() {
// Do any additional setup after loading the view, typically from a nib.

override func didReceiveMemoryWarning() {
// Dispose of any resources that can be recreated.

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 5

// make a cell for each cell index path
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

// get a reference to our storyboard cell
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("MyCollectionViewCell", forIndexPath: indexPath) as! MyCollectionViewCell
if(indexPath.row == 0) { //for first cell in the collection
cell.backgroundColor = UIColor.redColor()
} else {
cell.backgroundColor = UIColor.blueColor()

return cell


by this code my output is


Issue is when I click on first
it works but by selecting others my two colors are same


In your viewDidLoad reload the collectionView and after that explicitly select the first cell like this way.

let indexPath = NSIndexPath(forItem: 0, inSection: 0)
collView.selectItemAtIndexPath(indexPath, animated: true, scrollPosition: .None)

Note : Now there is no need to add code of color changing inside your cellForIteamAtIndexPath remove that code.