3

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

Sergey
  • 47,222
  • 25
  • 87
  • 129

3 Answers3

20

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

Guillaume Algis
  • 10,705
  • 6
  • 44
  • 72
Toploulou
  • 1,220
  • 10
  • 10
3

Another solution I found is using UITapGestureRecognizer:

UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc]
                                               initWithTarget:self action:@selector(showUserPopover:)];
        [tapRecognizer setNumberOfTouchesRequired:1];
        [tapRecognizer setDelegate:self];
        cell.userInteractionEnabled = YES;
        [cell addGestureRecognizer:tapRecognizer];

But the didSelectItemAtIndexPath solution is much better.

Sergey
  • 47,222
  • 25
  • 87
  • 129
3

swift 4 of @sergey answer

override public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: conversationCellIdentifier, for: indexPath) as! Cell
    cell.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleCellSelected(sender:))))
    return cell
}

@objc func handleCellSelected(sender: UITapGestureRecognizer){
   let cell = sender.view as! Cell
    let indexPath = collectionView?.indexPath(for: cell)
}
knig_T
  • 1,916
  • 16
  • 16