Как добавить событие в ячейки UICollectionView?

Я хочу обработать постукивание по ячейкам UICollectionView. Попытался добиться этого с помощью следующего кода:

-(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
{
     //...
}

Но исполнение прерывается на линии [cell addTarget:...] со следующей ошибкой:

- [UICollectionViewCell addTarget: action: forControlEvents:]: нераспознанный селектор, отправленный экземпляру 0x9c75e40

3 ответа

Решение

Вам следует реализовать протокол UICollectionViewDelegate, и вы найдете метод:

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

который говорит вам, когда пользователь касается одной ячейки

swift 4 из @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)
}

Другое решение, которое я нашел, использует UITapGestureRecognizer:

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

Но решение didSelectItemAtIndexPath намного лучше.

Другие вопросы по тегам