Search code examples
iosswiftuitableviewuilongpressgesturerecogni

swift: long press gesture reconizer doesn work


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?


Solution

  • 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);
        }
    }