我想处理点击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
答案 0 :(得分:19)
你应该实现UICollectionViewDelegate protocol,你会找到方法:
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
告诉您用户何时触摸一个单元格
答案 1 :(得分:2)
我找到的另一个解决方案是使用UITapGestureRecognizer:
UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc]
initWithTarget:self action:@selector(showUserPopover:)];
[tapRecognizer setNumberOfTouchesRequired:1];
[tapRecognizer setDelegate:self];
cell.userInteractionEnabled = YES;
[cell addGestureRecognizer:tapRecognizer];
但是didSelectItemAtIndexPath解决方案要好得多。
答案 2 :(得分:2)
快速回答@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)
}