[英]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.