Search code examples
objective-ciosxcodeuitableviewios5

UILongPressGestureRecognizer not works with tableview


I had added a UILongPressGestureRecognizer to a tableview in my ViewDidLoad method. I added this to detect long press on table view in my code. But it never works. In ViewDidLoad I added this code :

UILongPressGestureRecognizer *lpgr = [[UILongPressGestureRecognizer alloc] 
                                      initWithTarget:self action:@selector(handleLongPress:)];
lpgr.minimumPressDuration = 2.0; //seconds
lpgr.delegate = self;
[self.resultTableView addGestureRecognizer:lpgr];
[lpgr release];

I also added this method :

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

    NSIndexPath *indexPath = [self.resultTableView 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);
    }


}

Please help me to resolve this?


Solution

  • Your code is working. I think you have to add UIGestureRecognizerDelegate delegate in .h file or how to declare resultTableView i mean you define programmatically or using .xib file.Check it once.

    I have tried like this.

         resultTableView = [[UITableView alloc] init];
         resultTableView =[[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, 420) style:UITableViewStylePlain];
        resultTableView.rowHeight = 100.0;
        resultTableView.delegate=self;
         resultTableView.dataSource=self;
        [self.view addSubview:resultTableView];
    
        UILongPressGestureRecognizer *lpgr = [[UILongPressGestureRecognizer alloc] 
                                              initWithTarget:self action:@selector(handleLongPress:)];
        lpgr.minimumPressDuration = 2.0; //seconds
        lpgr.delegate = self;
        [resultTableView addGestureRecognizer:lpgr];
        [lpgr release];