3

我想处理点击 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

4

3 回答 3

20

你应该实现UICollectionViewDelegate 协议,你会发现方法:

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

告诉您用户何时触摸一个单元格

于 2013-07-30T10:57:22.527 回答
3

我发现的另一个解决方案是使用 UITapGestureRecognizer:

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

但是 didSelectItemAtIndexPath 解决方案要好得多。

于 2013-07-30T11:10:51.723 回答
3

swift 4 of @sergey 回答

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)
}
于 2018-02-13T15:26:23.037 回答