【问题标题】:How to add event to UICollectionView cells?如何向 UICollectionView 单元格添加事件?
【发布时间】:2013-07-30 10:52:34
【问题描述】:

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

【问题讨论】:

    标签: objective-c cocoa-touch uicollectionview target-action


    【解决方案1】:

    你应该实现UICollectionViewDelegate protocol,你会找到方法:

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

    当用户触摸一个单元格时告诉你

    【讨论】:

    • 这仅在触摸事件适用于整个单元格时才有效。
    【解决方案2】:

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

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

    但 didSelectItemAtIndexPath 解决方案要好得多。

    【讨论】:

    • 帮助了我,因为我在另一个滚动视图中重复使用了单元格。
    【解决方案3】:

    @sergey 的 4 个快速回答

    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)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-11
      • 2016-07-08
      相关资源
      最近更新 更多