2015-09-07 98 views
2

我正在寻找一种方法来查找给定(x,y)坐标处UILabel的值(文本)。在Swift中获取UILabel在坐标(x,y)处的值

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

例如(30,40)将返回标签值在那个位置。

谢谢!

更新

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) 
} 
+0

不用协调工作,为什么不使用标签? –

+0

查看标题“在视图中打击测试”下的UIView文档。根据所有的子视图是否为标签,你可以使用'hitTest:withEvent:'或'pointInside:withEvent:'。 –

回答

1

您可以通过hit-testing做到这一点。

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

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

在斯威夫特,它看起来像

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 
    } 
} 
+0

谢谢!你能否告诉我Swift语法看起来如何?我不熟悉obj-c。 – Daniel

+0

'@IBAction FUNC抽头(发件人:UITapGestureRecognizer){ VAR坐标= sender.locationInView(GraphView()?) getLabel(坐标) } FUNC getLabel(位置:CGPoint){ 设视图= self.view。 hitTest(location,withEvent:nil) println(view) println(view.text) }'你能帮忙吗? – Daniel

+0

您可以编辑您的问题,通过添加您尝试过的代码来更新它。还请提及您使用代码时遇到的问题,以帮助其他读者解决问题。 – 2015-09-07 16:27:03