views:

69

answers:

2

Hi,

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

Particularly the gesture recognize on UITableView ?

A: 

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

Thomas Joulin
Thanks for your answer but how can i detect which row is concerned by the touch ?
foOg
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.
Thomas Joulin
I'm sure that there is an easier way to do that, anyway if you have another idea, i'll be here :)
foOg
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
Thomas Joulin
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
+1  A: 

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
        NSLog(@"long press on table view at row %d", indexPath.row);
}

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 before user lifts their finger.

aBitObvious
Awesome !!! Thanks a lot! But a last little question: Why is the method handleLongPress is call when the touch ended ???
foOg
It's not called when touch ends but can fire multiple times if the user keeps their finger on the cell for more than 4 seconds (in this example) before lifting it.
aBitObvious
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) ...`.
aBitObvious