在iOS应用中,我有一个UITableView(不是UITableViewController的一部分),我想使用以下方法在自定义UITableViewCells上检测长按:

- (void)viewDidLoad
{
    myTableView.delegate=self;
    myTableView.dataSource=self;

    UILongPressGestureRecognizer *longTap = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longTapGestureCaptured:)];
    longTap.minimumPressDuration=0.5f;
    longTap.delegate=self;
    [myTableView addGestureRecognizer:longTap];
    [super viewDidLoad];
}

-(void)longTapGestureCaptured:(UILongPressGestureRecognizer *)gesture
{
    NSLog(@"Long tap"); // never called
}


但是,当我长按时,从未调用过longTapGestureCaptured。如何解决?

最佳答案

我尝试了您的代码。 100%为我工作。但是代码中的小变化是...

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    //Create cell here
    UITableViewCell *cell;
    cell= (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];

    //Add gesture to cell here
    UILongPressGestureRecognizer *longTap = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longTapGestureCaptured:)];
    longTap.minimumPressDuration=1.5f;
    longTap.delegate=self;
    [cell addGestureRecognizer:longTap];

    cell.textLabel.text = @"Name";//Send your data here

    return cell;

}

-(void)longTapGestureCaptured:(UILongPressGestureRecognizer *)gesture
{
    NSLog(@"Long tap"); // never called
}

10-08 06:08