Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

long press gesture on table view cell

I want two interactions on a table view cell: normal tap and long press. I used the answer to the following to help me get started:

Long press on UITableView

The problem with that is if I do a long press on a valid cell, the cell will highlight blue, and the long press gesture does not fire (it thinks its just a simple tap). However, if I start the long press gesture on a non-valid cell, then slide my finger over to a valid cell then release, it works just fine.

like image 326
user1120008 Avatar asked Feb 20 '12 20:02

user1120008


2 Answers

There is probably a better answer out there, but here is one way to do it:

First create a long press gesture recognizer on the table view itself.

UILongPressGestureRecognizer* longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(onLongPress:)];
[self.tableView addGestureRecognizer:longPressRecognizer];

Then, handle it with a routine that can find the selected row:

-(void)onLongPress:(UILongPressGestureRecognizer*)pGesture
{
if (pGesture.state == UIGestureRecognizerStateRecognized)
{
    //Do something to tell the user!
}
if (pGesture.state == UIGestureRecognizerStateEnded)
{
    UITableView* tableView = (UITableView*)self.view;
    CGPoint touchPoint = [pGesture locationInView:self.view];
    NSIndexPath* row = [tableView indexPathForRowAtPoint:touchPoint];
    if (row != nil) {
        //Handle the long press on row
    }
}
}

I haven't tried it, but I think you could keep the row from showing selection by making the gesture recognizers on the table view wait for the long press to fail.

like image 190
Prof Von Lemongargle Avatar answered Nov 02 '22 11:11

Prof Von Lemongargle


I came across the same problem and found a good solution. (at least on iOS 7)

Add this UILongPressGestureRecognizer to the cell itself.

self.longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(onSelfLongpressDetected:)];
[self addGestureRecognizer:self.longPressGesture];

Its weird but important to init with the target to self, AND also add the gestureRecognizer again to self and the method onSelfLongpressDetectedgets called.

like image 2
Fabio Berger Avatar answered Nov 02 '22 09:11

Fabio Berger