我使用下面的代碼來檢測對UITableView的點擊,並根據單擊哪個單元格和單元格中的哪個元素進行操作,並對任何不匹配的元素執行默認操作。如何在表格末尾添加indexPath爲空格的第一個單元格的indexPath?
-(void)addTapRecognizer {
// this is called when the view is created
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
singleTap.delegate = self;
singleTap.numberOfTapsRequired = 1;
singleTap.numberOfTouchesRequired = 1;
[self.tableView addGestureRecognizer:singleTap];
}
- (void)handleTap:(UITapGestureRecognizer *)tap {
NSLog(@"tap detected!");
if (UIGestureRecognizerStateEnded != tap.state) {
return;
}
UITableView *tableView = (UITableView *)tap.view;
CGPoint p = [tap locationInView:tap.view];
NSIndexPath* indexPath = [tableView indexPathForRowAtPoint:p];
[tableView deselectRowAtIndexPath:indexPath animated:NO];
NSLog(@"selectedIndex = %ld", (long)indexPath.row);
// take action depending where the cell was clicked
// with a default action if no element matches
MyTableViewCell *cell = (MyTableViewCell *) [self.tableView cellForRowAtIndexPath:indexPath];
CGPoint pointInCell = [tap locationInView:cell];
if(CGRectContainsPoint(cell.someImage.frame,pointInCell)) {
[self openItemID:[ItemList[indexPath.row] valueForKey:ID_ITEM]];
return;
}
if (...) {
...
return;
}
[self openItemID:[ItemList[indexPath.row] valueForKey:ID_ITEM]];
return;
}
我的問題是,當沒有足夠的細胞,以填補屏幕(所以例如表包含2個細胞,然後在下面空格),當最後一個單元格下方的用戶點擊,這是處理作爲第一個單元格的點擊(控制檯在兩種情況下都會記錄「selectedIndex = 0」)。
有沒有辦法區分這種點擊在表格末尾的空白處和單擊表格的「正確」單元格之間的區別?
我想知道在這種情況下'indexPath'' nil'。我不會奇怪,'nilIndexPath.row'值爲0. – Larme
Ooh ... spot on,我不認爲nil.row會給0,indexPath是零而不是。謝謝!雖然我仍然對Gordonium的答案感興趣,這似乎是一個更清晰的方法來做到這一點 – user14764
顯然,只需要檢測'UITableViewCell'上的選擇必須使用'tableView:didSelectRowAtIndexPath:'完成。但有些人有時想在他們身上添加多個手勢,所以你的問題似乎是合法的。 – Larme