迅速:长按手势调整器不起作用

时间:2018-10-23 10:44:09

标签: ios swift uitableview uilongpressgesturerecogni

我有一个UITableView,我想为每一行添加UILongPressGestureRecognizer。 我尝试将识别器拖到表单元格上并为其引用一个操作,但是从未调用过。

我也尝试过

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: ident, for: indexPath) as! TableViewCell
        /*...*/
    var longGesture = UILongPressGestureRecognizer(target: self, action: #selector(FilterPickerViewController.longPress))
    longGesture.minimumPressDuration = 1
    cell.leftLabel.addGestureRecognizer(longGesture)
    return cell
}

@objc func longPress(_ sender: UILongPressGestureRecognizer) {
    print("press")
}

但是那也不起作用。我在做什么错了?

1 个答案:

答案 0 :(得分:2)

您必须将长按手势识别器添加到表格视图中:

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

然后在手势处理程序中:获取单元格索引:-

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

    NSIndexPath *indexPath = [self.myTableView indexPathForRowAtPoint:p];
    if (indexPath == nil) {
        NSLog(@"long press on table view but not on a row");
    } else if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {
        NSLog(@"long press on table view at row %ld", indexPath.row);
    } else {
        NSLog(@"gestureRecognizer.state = %ld", gestureRecognizer.state);
    }
}