2013-07-30 72 views
2

我想要處理攻絲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:]: unrecognized selector sent to instance 0x9c75e40

回答

18

您應該實現UICollectionViewDelegate protocol,你會找到方法:

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

,告訴你,當用戶觸摸一個細胞

+0

這隻能如果觸摸事件適用於整個小區的迅速4。 –

2

我找到了另一種解決方案是使用UITapGestureRecognizer:

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

但didSelectItemAtIndexPath解決方案要好得多。

+0

幫助我,因爲我在另一個滾動視圖中重用了單元格。 – Caro

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) 
} 
相關問題