当我触摸(触摸) UITableViewCell 时,我的 ViewController 的 UITableViewDelegate 方法- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath叫做。此时我还需要获取 Touch-Point 的 x 坐标,以便我可以知道 Cell 的哪一部分被触摸(非附件项目)。我尝试过使用常用的触摸方法,例如 TouchesDidEnd,但无论我触摸何处(ViewController 中 UITableView 对象中的自定义 UITableViewCell 中的位置),坐标始终返回 x=0.000 y=0.000。我还尝试在 Custom Cell 类中实现触摸处理,虽然我可以获得准确的坐标,但我找不到将这些坐标传达给我的 ViewController 类(具有 UITableView)的方法。
Q: 当我触摸自定义 UITableViewCell 时,有没有一种好的方法可以获取设备屏幕的 x 坐标?
1. 在你的tableView中添加一个tapGestureRecognizer
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.tableViewTapped(recognizer:)))
tableView.addGestureRecognizer(tapGestureRecognizer)
2.编写一个函数来处理tapGesture
@objc func tableViewTapped(recognizer: UITapGestureRecognizer) {
let location = recognizer.location(in: self.tableView) // point of touch in tableView
if let indexPath = self.tableView.indexPathForRow(at: location) { // indexPath of touch location
if let cell = tableView.cellForRow(at: indexPath) as? MyCustomCell {
let locationInCell = recognizer.location(in: cell) // point of touch in cell
// do something with location or locationInCell
if cell.imageView.frame.contains(location) || cell.imageView.frame.contains(locationInCell) {
print("ImageView inside cell tapped!")
}
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)