在Swift的坐标(x,y)处获取UILabel的值

时间:2015-09-07 15:37:01

标签: ios swift uilabel coordinates

我正在寻找一种在给定(x,y)坐标处找到UILabel的值(文本)的方法。

所有其他问题似乎都是关于获取标签的(x,y),我试图做相反的事情......

例如(30,40)将返回该位置的Label值。

谢谢!

更新

func getLabel(location: CGPoint){

  let view = self.view.hitTest(location, withEvent:nil)
  //I would like to get the value of the label here but I'm not sure how to. 

}

@IBAction func tap(sender: UITapGestureRecognizer) {
    var coordinate = sender.locationInView(GraphView?())
    getLabel(coordinate)
}

1 个答案:

答案 0 :(得分:1)

您可以通过hit-testing完成此操作。

将您想要的点传递给顶级视图,它将返回包含该点的视图层次结构中最深的视图。

UIView *view = [self.view hitTest:location withEvent:nil];

在Swift中,它看起来像

let selectedView = view.hitTest(location, withEvent: nil)

<强>更新

您需要将标签userInteractionEnabled设置为true才能使标签注册该匹配。

您需要检查返回的视图以查看它是否为标签,然后检查它是否有任何文字。

if let label = selectedView as? UILabel
{
    if label.text!
    {
        // .. do what you want with the label's text
    }
}