ios - swift:长按手势识别器不起作用

标签 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")
}

但这也没有用。我做错了什么?

最佳答案

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

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);
    }
}

关于ios - swift:长按手势识别器不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52947075/

相关文章:

iOS — 粘性分段控件,如 App Store 应用程序

ios - 如何在 Xcode 中访问 DCIM

swift - 自动初始化器继承的条件是初始化器的签名

ios - 用户使用滑动手势编辑时如何离开 UITableViewCell EditingStyle 删除模式

ios - 无法以编程方式设置 UINavigationItem 标题

ios - 使用 `self.navigationController?.popViewController(animated: true)` 是关闭当前的 ViewController 还是只是返回到前一个?

iOS-swift 导航 Controller 样式不正确

iOS swift : How to create object like UIAlertView that seemingly nils itself out after dismissal

iphone - 如何通过自定义 UITableViewCell 的按钮单击来 popViewController

ios - 如何在 UITableView 上设置 VoiceOver 初始焦点