簡體   English   中英

TableView addGesture到UIImageView來知道哪個單元被點擊

[英]TableView addGesture to UIImageView to know which cell was tapped

我創建帶有部分的tableView,使用自定義單元格,並以這種方式在其中定義帶圖像的復選框(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];
}

但是我只有這里一行,不知道用戶點擊哪一行。 是否有可能認識到它?

如果您像這樣在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)];
}

而不是在cellForRowAtIndexPath的復選框(單元格中的按鈕)上添加手勢,而是在cell(StandardCellWithImage)本身中實現按鈕動作並從那里調用委托。

  1. 將動作設置為單元格中的按鈕,並在其中自行實現。
  2. 在didcell中聲明一個協議並在其中聲明所需的方法,如didSelectedImageAtIndexPath:
  3. 在您的視圖控制器中實現此協議
  4. 將cellForRowAtIndexPath中的單元格委托設置為selt(視圖控制器)
  5. 當您點擊復選框時,單元格中的方法將被調用,您將其設置為復選框按鈕的動作。
  6. 從那里調用委托方法didSelectedImageAtIndexPath:。 當然,您可以使用[[UITableView *)self.superview indexPathForCell:self]從那里返回indexPath對象。 //這里self = custon細胞對象

注意:

您可以在表格的數據源的-tableView:cellForRowAtIndexPath:中設置的單元格中存儲對tableView的弱引用。 這樣做會更好,因為依靠self.superview始終完全是tableView是脆弱的。 誰知道Apple將來可能如何重新組織UITableView的視圖層次結構。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM