简体   繁体   中英

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.

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.

I had a problem close to this. First I tried to add a long press gesture to an UIView inside a selectable cell and it didn't work. The solution was to add the gesture to the cell itself, like it was said before in Fabio's answer.

Adding the solution in swift bellow:

let longPress = UILongPressGestureRecognizer.init(target: self, action: #selector(longPress(_:)))
longPress.minimumPressDuration = 1.0
cell.addGestureRecognizer(longPress)

I used the code above inside the UITableViewDataSource method cellForRowAtIndexPath.

可能在IB中或以编程方式禁用选择

[cell setSelectionStyle:UITableViewCellSelectionStyleNone];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM