3 回答

TA貢獻1828條經驗 獲得超4個贊
首先將長按手勢識別器添加到表格視圖中:
UILongPressGestureRecognizer *lpgr = [[UILongPressGestureRecognizer alloc]
initWithTarget:self action:@selector(handleLongPress:)];
lpgr.minimumPressDuration = 2.0; //seconds
lpgr.delegate = self;
[self.myTableView addGestureRecognizer:lpgr];
[lpgr release];
然后在手勢處理程序中:
-(void)handleLongPress:(UILongPressGestureRecognizer *)gestureRecognizer
{
CGPoint p = [gestureRecognizer locationInView:self.myTableView];
NSIndexPath *indexPath = [self.myTableView indexPathForRowAtPoint:p];
if (indexPath == nil) {
NSLog(@"long press on table view but not on a row");
} else if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {
NSLog(@"long press on table view at row %ld", indexPath.row);
} else {
NSLog(@"gestureRecognizer.state = %ld", gestureRecognizer.state);
}
}
您必須注意這一點,以免干擾用戶對單元格的正常輕敲,并注意handleLongPress可能會觸發多次(這是由于手勢識別器狀態更改)。

TA貢獻1820條經驗 獲得超2個贊
我已經使用了安娜·卡列尼娜(Anna-Karenina)的答案,并且在出現嚴重錯誤的情況下效果很好。
如果您使用的是節,則長按節標題將導致您在按該節的第一行時得到錯誤的結果,我在下面添加了一個固定版本(包括根據手勢狀態過濾虛擬呼叫, Anna-Karenina的建議)。
- (IBAction)handleLongPress:(UILongPressGestureRecognizer *)gestureRecognizer
{
if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {
CGPoint p = [gestureRecognizer locationInView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:p];
if (indexPath == nil) {
NSLog(@"long press on table view but not on a row");
} else {
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
if (cell.isHighlighted) {
NSLog(@"long press on table view at section %d row %d", indexPath.section, indexPath.row);
}
}
}
}
- 3 回答
- 0 關注
- 956 瀏覽
添加回答
舉報