如何找出 UITableView 中的哪一行收到了强制触摸事件?

How to find out which particular row in a UITableView received a force-touch event?

我正在尝试在 UITableView 上实现 3D 触摸。 subclassed UITableView 中的以下代码有效:

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touch = touches.first!
    if touch.force <= (touch.maximumPossibleForce / 2) {
        super.touchesBegan(touches, with: event)
    }
    else {
        print("force touch called !!!")
    }
}

但是,我怎么知道 table 中的特定行被强制触摸了?

调试时touch.view被识别为"UITableViewCellContentView"对象,但UIKit中不存在这个class。转换它会导致 "Could not cast value of type 'UITableViewCellContentView' (0x107cbab80) to 'UITableViewCell' (0x107cbab30)." 运行时错误。

如何找出 UITableView 中的哪一行接收到强制触摸事件? 我正在使用 Swift 4.2 和 iOS 12.1。

谢谢!

内容视图是单元格内的视图,您不能简单地将其转换为 UITableViewCell,因为它是不相关的类型。

您可以在 table 视图的坐标系中使用 indexPathForRow(at:) to convert a CGPoint into an IndexPath. You will need to convert 触摸点,而不是内容视图。

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touch = touches.first!
    if touch.force <= (touch.maximumPossibleForce / 2) {
        super.touchesBegan(touches, with: event)
    }
    else {
        print("force touch called !!!")
        let tablePoint = touch.location(in:self)
        if let indexPath = self.indexPathForRow(at:tablePoint) {
            print("\(indexPath.row) touched")
        }
    }
}

根据您尝试执行的操作,您可能会发现通过 registerForPreviewingUIViewControllerPreviewingDelegate

在视图控制器中处理压力触摸更容易