如何在tableview中检测双击/触摸事件

时间:2014-03-15 12:29:29

标签: ios iphone objective-c uitableview

经过漫长但徒劳无功的搜索,我无法在我的桌面视图中检测到双击/触摸事件,实际上想要在任何TableViewCell上双击调用详细视图,实际上我不会# 39;甚至不知道如何去做。

到目前为止,这是我的代码......

viewDidLoad

UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self    action:@selector(handleTapGesture:)];
tapGesture.numberOfTapsRequired = 2;
[self.myTable addGestureRecognizer:tapGesture];

handleTapGesture 方法是

- (void)handleTapGesture:(UITapGestureRecognizer *)sender {
  if (sender.state == UIGestureRecognizerStateRecognized) {
      flag = true;
  }
}

最后触摸或点击tableview的单元格 委托方法是

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (flag == true)
    {
        DetailInvoicing *detail = [[DetailInvoicing alloc] initWithNibName:@"DetailInvoicing" bundle:nil];
        detail.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
        detail.customerName = [customerArray objectAtIndex:indexPath.row];
        [self presentViewController:detail animated:YES completion:nil];
    }
}

如果删除此标志条件,则只需单击即可调用新视图。 我错在哪里或者还有其他方法可以做到。

3 个答案:

答案 0 :(得分:9)

有一个简单的方法,不使用UITapGestureRecognizer也不实现自定义表视图类。

@implementation MyTableViewController
NSTimeInterval lastClick;
NSIndexPath *lastIndexPath;

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSTimeInterval now = [[[NSDate alloc] init] timeIntervalSince1970];
    if ((now - lastClick < 0.3) && [indexPath isEqual:lastIndexPath]) {
        // Double tap here
        NSLog(@"Double Tap!");
    }
    lastClick = now;
    lastIndexPath = indexPath;
}
@end

只是查看代码行。

答案 1 :(得分:2)

修正了Swift 3.1

   func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) 
    {

    let now: TimeInterval = Date().timeIntervalSince1970
    if (now - lastClick < 0.3) && (lastIndexPath?.row == indexPath.row )
    {
        print("Double Tap!")
    }
    lastClick = now
    lastIndexPath = indexPath
    }

答案 2 :(得分:-1)

尝试这样,在customtableview类中实现以下方法: -

 - (void)touchesEnded:(NSSet *)touches 
    withEvent:(UIEvent *)event {
    UITouch *aTouch = [touches anyObject];
  // below numberofclick in integer type
   self.numberOfClicks = [aTouch tapCount];
 [super touchesEnded:touches withEvent:event];
 }

现在在你的tableview委托方法(didSelectRowAtIndexPath)中。然后检测numberOfclicks是否为2或1并相应地修改您的条件。下面是代码行,您可以在代理方法中检测按下的分接头数

   if (myCell.numberOfClicks == 2) {
   NSLog(@"Double clicked");   }}