如何找出UITableView中哪个特定行收到强制触摸事件?

问题描述 投票:1回答:1

我正在尝试在UITableView上实现3D触控。子类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 !!!")
    }
}

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

在调试时,touch.view被标识为“UITableViewCellContentView”对象,但UIKit中不存在此类。转换它会导致“无法将类型'UITableViewCellContentView'(0x107cbab80)的值转换为'UITableViewCell'(0x107cbab30)。”运行时错误。

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

谢谢!

ios uitableview swift4
1个回答
1
投票

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

您可以使用indexPathForRow(at:)将CGPoint转换为IndexPath。您需要在表视图的坐标系中使用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更轻松地处理视图控制器中的力触摸

© www.soinside.com 2019 - 2024. All rights reserved.