UICollectionViewDelegate setup and item selection

suggest change

Sometimes, if an action should be bound to a collection view’s cell selection, you have to implement the UICollectionViewDelegate protocol and set the collection view’s delegate to that object.

Let’s say the collection view’s controller is MyViewController.

Objective-C

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

@interface MyViewController : UIViewController <UICollectionViewDelegate, UICollectionViewDataSource>

Swift

In MyViewController.swift add the following. This is Swift 2.

class MyViewController: UIViewController, 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 the selected cell to green. The force-unwrap crashes if cellForItemAtIndexPath returns nil, and the color disappears when the cell is reused unless cellForItemAtIndexPath applies it again.

Objective-C

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

Swift

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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents