196

I would like to handle a long press on a UITableViewCell to print a "quick access menu". Did someone already do this?

Particularly the gesture recognize on UITableView?

10 Answers 10

435

First 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:

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

You have to be careful with this so that it doesn't interfere with the user's normal tapping of the cell and also note that handleLongPress may fire multiple times (this will be due to the gesture recognizer state changes).

14
  • 2
    Awesome !!! Thanks a lot! But a last little question: Why is the method handleLongPress is call when the touch ended ???
    – foOg
    Oct 13, 2010 at 15:15
  • 113
    Correction: it fires multiple times to indicate the different states of the gesture (began, changed, ended, etc). So in the handler method, check the state property of the gesture recognizer to avoid doing the action at each state of the gesture. Eg: if (gestureRecognizer.state == UIGestureRecognizerStateBegan) ....
    – user467105
    Oct 18, 2010 at 15:12
  • 4
    Don't forget, gesture recognizers can now be added to UI elements directly in Interface Builder and connected through an IBAction method, so this answer is even easier ;-) (just remember to attach the recognizer to the UITableView, not the UITableViewCell...)
    – user577537
    Jun 26, 2012 at 15:51
  • 11
    Also confirm to UIGestureRecognizerDelegate protocol in class.h file
    – jay
    Aug 9, 2012 at 5:30
  • 2
    How do you prevent the table view from navigating into the cell (if you have 'didSelectRowAtIndexPath' implemented?)
    – Marchy
    Sep 15, 2016 at 17:45
47

I've used Anna-Karenina's answer, and it works almost great with a very serious bug.

If you're using sections, long-pressing the section title will give you a wrong result of pressing the first row on that section, I've added a fixed version below (including the filtering of dummy calls based on the gesture state, per Anna-Karenina suggestion).

- (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
40

Answer in Swift 5 (Continuation of Ricky's answer in Swift)

Add the UIGestureRecognizerDelegate to your ViewController

 override func viewDidLoad() {
    super.viewDidLoad()

    //Long Press
    let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress))
    longPressGesture.minimumPressDuration = 0.5
    self.tableView.addGestureRecognizer(longPressGesture)
 }

And the function:

@objc func handleLongPress(longPressGesture: UILongPressGestureRecognizer) {
    let p = longPressGesture.location(in: self.tableView)
    let indexPath = self.tableView.indexPathForRow(at: p)
    if indexPath == nil {
        print("Long press on table view, not row.")
    } else if longPressGesture.state == UIGestureRecognizer.State.began {
        print("Long press on row, at \(indexPath!.row)")
    }
}
0
22

Here are clarified instruction combining Dawn Song's answer and Marmor's answer.

Drag a long Press Gesture Recognizer and drop it into your Table Cell. It will jump to the bottom of the list on the left.

enter image description here

Then connect the gesture recognizer the same way you would connect a button. enter image description here

Add the code from Marmor in the the action handler

- (IBAction)handleLongPress:(UILongPressGestureRecognizer *)sender {
if (sender.state == UIGestureRecognizerStateBegan) {

    CGPoint p = [sender 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);
        }
    }
}

}

2
  • 3
    The best answer in my opinion Dec 4, 2015 at 21:48
  • 9
    Long Press Gesture Recognizer should be applied to table view not table view cell. Dropping it to table view cell will only have row 0 listening to long press.
    – Alex
    Oct 1, 2016 at 4:22
15

Looks to be more efficient to add the recognizer directly to the cell as shown here:

Tap&Hold for TableView Cells, Then and Now

(scroll to the example at the bottom)

2
  • 7
    How can allocating a new gesture recognizer object for each row be more efficient than a single recognizer for the whole table? Dec 23, 2011 at 17:50
  • 8
    Remember though there is only a few cells created if dequeue is working correctly.
    – Ants
    Feb 7, 2012 at 22:55
15

Answer in Swift:

Add delegate UIGestureRecognizerDelegate to your UITableViewController.

Within UITableViewController:

override func viewDidLoad() {
    super.viewDidLoad()

    let longPressGesture:UILongPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: "handleLongPress:")
    longPressGesture.minimumPressDuration = 1.0 // 1 second press
    longPressGesture.delegate = self
    self.tableView.addGestureRecognizer(longPressGesture)

}

And the function:

func handleLongPress(longPressGesture:UILongPressGestureRecognizer) {

    let p = longPressGesture.locationInView(self.tableView)
    let indexPath = self.tableView.indexPathForRowAtPoint(p)

    if indexPath == nil {
        print("Long press on table view, not row.")
    }
    else if (longPressGesture.state == UIGestureRecognizerState.Began) {
        print("Long press on row, at \(indexPath!.row)")
    }

}
7

I put together a little category on UITableView based on Anna Karenina's excellent answer.

Like this you'll have a convenient delegate method like you're used to when dealing with regular table views. Check it out:

//  UITableView+LongPress.h

#import <UIKit/UIKit.h>

@protocol UITableViewDelegateLongPress;

@interface UITableView (LongPress) <UIGestureRecognizerDelegate>
@property(nonatomic,assign)   id <UITableViewDelegateLongPress>   delegate;
- (void)addLongPressRecognizer;
@end


@protocol UITableViewDelegateLongPress <UITableViewDelegate>
- (void)tableView:(UITableView *)tableView didRecognizeLongPressOnRowAtIndexPath:(NSIndexPath *)indexPath;
@end



//  UITableView+LongPress.m

#import "UITableView+LongPress.h"

@implementation UITableView (LongPress)
@dynamic delegate;

- (void)addLongPressRecognizer {
    UILongPressGestureRecognizer *lpgr = [[UILongPressGestureRecognizer alloc]
                                          initWithTarget:self action:@selector(handleLongPress:)];
    lpgr.minimumPressDuration = 1.2; //seconds
    lpgr.delegate = self;
    [self addGestureRecognizer:lpgr];
}


- (void)handleLongPress:(UILongPressGestureRecognizer *)gestureRecognizer
{
    CGPoint p = [gestureRecognizer locationInView:self];

    NSIndexPath *indexPath = [self indexPathForRowAtPoint:p];
    if (indexPath == nil) {
        NSLog(@"long press on table view but not on a row");
    }
    else {
        if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {
            // I am not sure why I need to cast here. But it seems to be alright.
            [(id<UITableViewDelegateLongPress>)self.delegate tableView:self didRecognizeLongPressOnRowAtIndexPath:indexPath];
        }
    }
}

If you want to use this in a UITableViewController, you probably need to subclass and conform to the new protocol.

It works great for me, hope it helps others!

1
  • Amazing usage of delegation and category patterns
    – valeCocoa
    Aug 8, 2017 at 22:53
6

Swift 3 answer, using modern syntax, incorporating other answers, and eliminating unneeded code.

override func viewDidLoad() {
    super.viewDidLoad()
    let recognizer = UILongPressGestureRecognizer(target: self, action: #selector(tablePressed))
    tableView.addGestureRecognizer(recognizer)
 }

@IBAction func tablePressed(_ recognizer: UILongPressGestureRecognizer) {
    let point = recognizer.location(in: tableView)

    guard recognizer.state == .began,
          let indexPath = tableView.indexPathForRow(at: point),
          let cell = tableView.cellForRow(at: indexPath),
          cell.isHighlighted
    else {
        return
    }

    // TODO
}
3

Just add UILongPressGestureRecognizer to the given prototype cell in storyboard, then pull the gesture to the viewController's .m file to create an action method. I made it as I said.

1
  • Can you explain a little more? Did you make the prototype cell a property in your VC? Jul 28, 2015 at 3:45
-2

Use the UITouch timestamp property in touchesBegan to launch a timer or stop it when touchesEnded got fired

5
  • Thanks for your answer but how can i detect which row is concerned by the touch ?
    – foOg
    Oct 13, 2010 at 14:05
  • I might be wrong, but nothing is provided to help you do that. You'll have to get the indexes of the current visible cells with [tableView indexPathsForVisibleRows] and then, using some calculations (your tableView offset from the top + X times the rows) you'll know that the coordinates of your finger is on which row. Oct 13, 2010 at 14:17
  • I'm sure that there is an easier way to do that, anyway if you have another idea, i'll be here :)
    – foOg
    Oct 13, 2010 at 14:32
  • I'd be glad to know too if something easier is possible. But I don't think there is, mostly because the is not the way Apple wants us to handle interactions... It looks like an Android way of thinking this "quick access menu". If it were my app, I'll handle it like the Twitter app. A swipe to the left displays the options Oct 13, 2010 at 14:37
  • Yes, i thought about that, so if i really can't do it with a long press event, i'll use the swipe method. But, maybe someone in stack-overflow did it ...
    – foOg
    Oct 13, 2010 at 14:47

Not the answer you're looking for? Browse other questions tagged or ask your own question.