[英]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)本身中实现按钮动作并从那里调用委托。
注意:
您可以在表格的数据源的-tableView:cellForRowAtIndexPath:中设置的单元格中存储对tableView的弱引用。 这样做会更好,因为依靠self.superview始终完全是tableView是脆弱的。 谁知道Apple将来可能如何重新组织UITableView的视图层次结构。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.