Change Background of UICollectionView Cell on Tap Change Background of UICollectionView Cell on Tap ios ios

Change Background of UICollectionView Cell on Tap


The problem is that you are changing the color on highlight and changing it back on deselect instead that on unhighlight

You should simply change this:

- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath{  UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];  cell.contentView.backgroundColor = [UIColor greenColor];}

to this:

- (void)collectionView:(UICollectionView *)collectionView didUnhighlightItemAtIndexPath:(NSIndexPath *)indexPath{  UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];  cell.contentView.backgroundColor = [UIColor greenColor];}

Also, if you don't want to wait a bit before getting your highlight happen you should set the delaysContentTouches property of the collection view to NO

Edit: also ensure that you call

[collectionView deselectItemAtIndexPath:indexPath animated:NO];

inside the -didSelectItemAtIndexPath method


Swift 3 version

Add the following two methods to your view controller class:

// change background color when user touches cellfunc collectionView(_ collectionView: UICollectionView, didHighlightItemAt indexPath: IndexPath) {    let cell = collectionView.cellForItem(at: indexPath)    cell?.backgroundColor = UIColor.red}// change background color back when user releases touchfunc collectionView(_ collectionView: UICollectionView, didUnhighlightItemAt indexPath: IndexPath) {    let cell = collectionView.cellForItem(at: indexPath)    cell?.backgroundColor = UIColor.green}

See here for help in setting up a basic collection view in Swift.


Edit: Answer in Swift 3

var selectedIndex = Int ()func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell    cell.backgroundColor = selectedIndex == indexPath.row ? UIColor.green : UIColor.red    return cell}func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath){    selectedIndex = indexPath.row    self.yourCollctionView.reloadData()}