1

I have a UITableView and I want to add UILongPressGestureRecognizer for each row. I tried dragging the recognizer on the table cell and referencing an action for it, but that was never called.

I also tried

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: ident, for: indexPath) as! TableViewCell
        /*...*/
    var longGesture = UILongPressGestureRecognizer(target: self, action: #selector(FilterPickerViewController.longPress))
    longGesture.minimumPressDuration = 1
    cell.leftLabel.addGestureRecognizer(longGesture)
    return cell
}

@objc func longPress(_ sender: UILongPressGestureRecognizer) {
    print("press")
}

but that didn't work either. What am i doing wrong?

AshvinGudaliya
  • 3,234
  • 19
  • 37
Ginso
  • 459
  • 17
  • 33

1 Answers1

2

You have to add the long press gesture recognizer to the table view:

UILongPressGestureRecognizer *lpgr = [[UILongPressGestureRecognizer alloc] 
  initWithTarget:self action:@selector(handleLongPress:)];
lpgr.minimumPressDuration = 2.0; //seconds
lpgr.delegate = self;
[self.myTableView addGestureRecognizer:lpgr];
[lpgr release];

Then in the gesture handler: get the cell index:-

-(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);
    }
}
user1376400
  • 614
  • 1
  • 4
  • 8
  • ty, that worked. Can you tell what the line [lpgr release] is needed for and how it translates to swift? it seems to work without it, though – Ginso Oct 23 '18 at 11:11