iOS UICollectionView UICollectionViewDelegate setup and item selection

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

Sometimes, if an action should be bind to a collection view's cell selection, you have to implement the UICollectionViewDelegate protocol.

Let's say the collection view is inside a UIViewController MyViewController.

Objective-C

In your MyViewController.h declares that it implements the UICollectionViewDelegate protocol, as below

@interface MyViewController : UIViewController <UICollectionViewDelegate, .../* previous existing delegate, as UICollectionDataSource *>

Swift

In your MyViewController.swift add the following

class MyViewController : UICollectionViewDelegate {
}

The method that must be implemented is

Objective-C

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
}

Swift

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)
{
}

As just an example we can set the background color of selected cell to green.

Objective-C

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

Swift

class MyViewController : UICollectionViewDelegate {
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)
    {
        var cell : UICollectionViewCell = collectionView.cellForItemAtIndexPath(indexPath)!
        cell.backgroundColor = UIColor.greenColor()
    }
}


Got any iOS Question?