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

前端 未结 1 1693
一整个雨季
一整个雨季 2021-01-14 23:05

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 try

相关标签:
1条回答
  • 2021-01-14 23:14

    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
        }
    }
    
    0 讨论(0)
提交回复
热议问题