ios - 将 TableView 点击位置转换为单元格 View 位置

标签 ios swift uitableview uitapgesturerecognizer

我的 TableView 上有一个 TapGestureRecognizer。 它让我找到了我点击过的手机。 接下来我想使用点击的位置来检查单元格上的标签是否被点击。 但当然我有相对于 TableView 而不是 CellView 的位置。 您知道将 TableView Location(“World”)转换为相应的 CellView Location(“Local”)的简便方法吗?

非常感谢。

到目前为止我的代码。 查看加载:

let tapGesture = UITapGestureRecognizer(target: self, action: #selector(MyTableViewController.tapEdit(recognizer:)))
        self.tableView.addGestureRecognizer(tapGesture)
        tapGesture.delegate = self

点击方法:

@objc func tapEdit(recognizer: UITapGestureRecognizer)  {

        if recognizer.state == UIGestureRecognizerState.ended {

            let tapLocation = recognizer.location(in: self.tableView)

            if let tapIndexPath = self.tableView.indexPathForRow(at: tapLocation) {

                print("Tap Location: \(tapLocation)")
                if let cell = self.tableView.cellForRow(at: tapIndexPath) as? MyTableViewCell {

                    // of course not working because of the relative location difference
                    if cell.myLabel.frame.contains(tapLocation) {
                        print("Taped cell at \(tapIndexPath). Hit Label.")
                    }

                }

            }

        }

    }

问候

最佳答案

如果您想获得该单元格的局部坐标,最简单的方法是使用它来获取该点击的位置:

@objc func tapEdit(recognizer: UITapGestureRecognizer)  {

    if recognizer.state == UIGestureRecognizerState.ended {

        let tapLocation = recognizer.location(in: self.tableView)

        if let tapIndexPath = self.tableView.indexPathForRow(at: tapLocation) {

            print("Tap Location: \(tapLocation)")
            if let cell = self.tableView.cellForRow(at: tapIndexPath) as? MyTableViewCell {
                let localLocation = recogniser.location(in: cell)
                // of course not working because of the relative location difference
                if cell.myLabel.frame.contains(localLocation) {
                    print("Taped cell at \(tapIndexPath). Hit Label.")
                }

            }

        }

    }

}

关于ios - 将 TableView 点击位置转换为单元格 View 位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50077034/

相关文章:

ios - CorePlot axisLine和gridLine的长度太长

iOS 9.0 - 获取键盘将显示/隐藏来自其他应用程序的通知

swift - 如何在收到通知且启用 Touch ID 时打开特定 ViewController

Swift SpriteKit : png image appears black while the game is being run. 我该如何解决这个问题?

ios - Swift: View Controller 内的 tableView 始终为 "found nil while unwr..."

ios - 选择 Cell 时将 UITableViewCell 置于顶部

ios - 将 UIImageView 添加到自定义 UITableView 单元格

ios - 列表项在 ipad 上的显示方式与任何其他设备不同

ios - 如何传递符合协议(protocol)的类类型

objective-c - 不鼓励使用 beginAnimations