2013-01-20 28 views
0

我創建的tableView使用節,我使用自定義單元格,並以這種方式與圖像定義有複選框(的UIImageView):的TableView addGesture到的UIImageView知道哪些細胞被竊聽

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

    static NSString *CellIdentifier = @"cellIdentifier"; 
    StandardCellWithImage *cell = (StandardCellWithImage *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

    if(cell == nil) { 
     cell = [[StandardCellWithImage alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
     cell.selectionStyle = UITableViewCellSeparatorStyleNone; 
    } 

    cell.checkbox.tag = indexPath.row; 
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didSelectedImageAtIndexPath:)]; 
    tapGesture.numberOfTapsRequired = 1; 
    tapGesture.delegate = self; 
    [cell.checkbox addGestureRecognizer:tapGesture]; 
    cell.checkbox.userInteractionEnabled = YES; 

    return cell; 
} 

而且在didSelectedImageAtIndexPath方法使用:

- (void) didSelectedImageAtIndexPath:(id) sender { 
    UITapGestureRecognizer *gesture = (UITapGestureRecognizer *) sender; 
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:gesture.view.tag inSection:0]; 
} 

但我在這裏只有一行沒有任何知識的哪一部分用戶點擊這一行。有沒有可能認出它?

回答

2

有關,如果你編碼view.tag內物品/節這樣的內容:

view.tag = indexPath.section * kMAX_SECTION_SIZE + indexPath.item; 

那麼你可以做:

- (void) didSelectedImageAtIndexPath:(id) sender { 
    UITapGestureRecognizer *gesture = (UITapGestureRecognizer *) sender; 


    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:gesture.view.tag % kMAX_SECTION_SIZE 
             inSection:int(gesture.view.tag/kMAX_SECTION_SIZE)]; 
} 
+0

好戲Sergio!謝謝 – edzio27

1

相反的複選框上添加手勢(在單元格鍵) cellForRowAtIndexPath,在單元(StandardCellWithImage)本身中實現按鈕操作,並從那裏調用委託。

  1. 將操作設置爲單元格&中的按鈕在其中實現它本身。
  2. 聲明細胞&申報方法的協議,它要作爲didSelectedImageAtIndexPath:
  3. 在您的視圖控制器
  4. 細胞
  5. 集代表在的cellForRowAtIndexPath實施此協議SELT(視圖控制器)
  6. 當您點擊在單元格中的複選框方法將被調用,您設置爲複選框按鈕的操作。
  7. 調用委託方法didSelectedImageAtIndexPath:從那裏。當然,你可以使用[(UITableView *)self.superview indexPathForCell:self]從那裏返回indexPath對象。 //這裏自= custon細胞對象

注:

可以存儲弱引用到的tableView中的單元格,這你會在-tableView設置:的cellForRowAtIndexPath:你的表的數據源。這是更好的,因爲依靠self.superview總是完全是tableView是脆弱的。誰知道蘋果將來如何重新組織UITableView的視圖層次結構。