繁体   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