How to add event to UICollectionView cells?

Sergey picture Sergey · Jul 30, 2013 · Viewed 18.3k times · Source

I want to handle tapping UICollectionView cells. Tried to achieve this by using the following code:

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{    
    static NSString *cellIdentifier = @"cvCell";    
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];  

    // Some code to initialize the cell

    [cell addTarget:self action:@selector(showUserPopover:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}

- (void)showUserPopover:(id)sender
{
     //...
}

But the execution breaks at the line [cell addTarget:...] with the following error:

-[UICollectionViewCell addTarget:action:forControlEvents:]: unrecognized selector sent to instance 0x9c75e40

Answer

Toploulou picture Toploulou · Jul 30, 2013

You should implement the UICollectionViewDelegate protocol and you'll find the method :

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

that tells you when the user touch one cell