首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在选择自定义UITableViewCell时获取触摸坐标?

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

Stack Overflow用户
提问于 2009-08-14 09:50:13
回答 4查看 7K关注 0票数 7

当我触摸(触摸)一个UITableViewCell我的视图控制器的UITableViewDelegate方法- (空)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath被调用。此时我还需要获得Touch-Point的x坐标,这样我才能知道单元格的哪个部分被触摸(非附件项)。我尝试过使用常用的触摸方法,比如TouchesDidEnd,但是无论我触摸哪里,坐标总是返回x=0.000 y=0.000 (在自定义UITableViewCell中的位置,在我的ViewController中的UITableView对象中)。我还尝试在Custom Cell类中实现触摸处理,虽然我可以获得准确的坐标,但是我找不到将这些坐标传递给我的ViewController类(它有UITableView)的方法。

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

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2009-12-31 15:54:14

在表视图上放置一个透明的UIView,覆盖它的-touchesBegan:withEvent:等方法。在这些被覆盖的方法中,获取UITouch对象并对其调用-locationInView:以获取CGPoint值。

这给了你一个触摸事件的坐标。

然后,您只需将这些UITouch事件传递给底层表视图。表视图处理将触动传递给行等日常事务。

票数 5
EN

Stack Overflow用户

发布于 2018-07-17 07:25:19

1.向tableView添加tapGestureRecognizer

代码语言:javascript
复制
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.tableViewTapped(recognizer:)))
tableView.addGestureRecognizer(tapGestureRecognizer)

2.编写处理tapGesture的函数

代码语言:javascript
复制
@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!")        
            }
        }
    }
}
票数 3
EN

Stack Overflow用户

发布于 2015-11-05 00:17:40

下面是什么:

代码语言:javascript
复制
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    let rect = tableView.rectForRow(at: indexPath as IndexPath)
    var point = CGPoint(x: rect.midX, y: rect.midY)
    point = tableView.convert(point, to: nil)
    print(point)
}
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1276988

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档