首页 > 解决方案 > UITableView 上未调用 LongPress 手势

问题描述

在 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 永远不会被调用。如何解决?

标签: iosobjective-cxcodeuitableviewuilongpressgesturerecogni

解决方案


我试过你的代码。它 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
}

推荐阅读