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.
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.
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 onSelfLongpressDetected
gets called.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With