如何在选择自定义UITableViewCell时获取触摸坐标?

Rex*_*ids 6 iphone cocoa-touch delegates uitableview ios

当我触摸(Touch Up)一个UITableViewCell我的ViewController的UITableViewDelegate方法- (void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath被调用.此时我还需要获得Touch-Point的x坐标,以便我可以知道Cell的哪个部分被触摸(非附件物品).我尝试使用常见的触摸方法,如TouchesDidEnd,但无论我在哪里触摸,坐标总是返回x = 0.000 y = 0.000(在我的ViewController中的UITableView对象中的自定义UITableViewCell中的位置).我也尝试在Custom Cell类中实现触摸处理,虽然我可以获得准确的坐标,但我无法将这些坐标传递给我的ViewController类(它有UITableView).

问:当我触摸自定义UITableViewCell时,是否有一种很好的方法可以获得设备屏幕的x坐标?

Doe*_*ata 7

1. 在你的tableView中添加一个tapGestureRecognizer

let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.tableViewTapped(recognizer:)))
tableView.addGestureRecognizer(tapGestureRecognizer)
Run Code Online (Sandbox Code Playgroud)

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!")        
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Ale*_*lds 5

UIView在表视图顶部放置透明,覆盖其-touchesBegan:withEvent:等方法.在那些重写的方法中,获取UITouch对象并调用-locationInView:它们以获取CGPoint值.

这为您提供了触摸事件的坐标.

然后,您只需将这些UITouch事件传递给基础表视图.表视图处理其通常接触行等的业务.