iOS UICollectionViewDelegate setup and item selection


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()
    }
}