Get value of UILabel at coordinate (x,y) in Swift

2020-03-26 08:36发布

I am looking for a way to find the value(text) of a UILabel at a given (x,y) coordinate.

All other questions seem to be about getting the (x,y) of a label, I am trying to do the opposite...

For example (30,40) would return the value of the Label at that location.

Thank you!

Update

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条回答
Evening l夕情丶
2楼-- · 2020-03-26 08:56

You can accomplish this by hit-testing.

Pass the point you want to the top-level view, and it will return the deepest view within the view hierarchy that contains that point.

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

In Swift, it would look like

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

Update:

You need to set the label's userInteractionEnabled to true for your labels to register the hit.

You'll need to check the returned view to see if it is a label, then check to see if it has any text.

if let label = selectedView as? UILabel
{
    if label.text!
    {
        // .. do what you want with the label's text
    }
}
查看更多
登录 后发表回答