Cesare
Cesare

Reputation: 9409

How do I change the background image of a UICollectionViewCell that has been tapped?

I have multiple UICollectionViewCells. When the user taps on a specific cell, I would like my app to change the background image of the touched cell.

My approach is to focus on the didSelectItemAtIndexPath method. When a cell is touched, this method will be called.

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    var cell: UICollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("cellIdentifier", forIndexPath: indexPath) as! UICollectionViewCell
    cell.backgroundView = UIImageView(image: UIImage(named: "myImage"))
}

However, I can't get it working but I don't know why. The issue is probably related to indexPath, that doesn't return a correct value of the cell. I tried using indexPath.row and this does actually return an Int number of the cell.

What's more, I'm also creating a new UICollectionViewCell with var but this cell already exists.

Why isn't the cell updating its background image? How do I change the background image of a UICollectionViewCell that has been touched by the user?

Upvotes: 1

Views: 1502

Answers (1)

Victor Sigler
Victor Sigler

Reputation: 23451

I totally agree with the Josh's answer, but if you change the background image using the didSelectItemAtIndexPath method it works fine as well. Then, you can use the cellForRowAtIndexPath method that returns the UITableViewCell at the specified indexPath, like in the following way:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {        
    var cell = tableView.cellForRowAtIndexPath(indexPath) as UITableViewCell!
    cell.backgroundView = UIImageView(image: UIImage(named: "photo2"))        
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell
    cell.backgroundView = UIImageView(image: UIImage(named: "photo1"))
    cell.selectionStyle = .None
    return cell
}

I just put the selectionStyle to .None to avoid the highlight. I hope this help you.

Upvotes: 4

Related Questions