我正在尝试在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。
谢谢!
内容视图是单元格内部的视图,您不能简单地将其转换为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")
}
}
}
根据您的尝试,您可能会发现通过registerForPreviewing
和UIViewControllerPreviewingDelegate
更轻松地处理视图控制器中的力触摸