Find the location of {x, y} text in uilabel

I have a line coming from a server that I'm showing on the UILabel multiline. It is within this line that I identify some specific substring. I want to put a button on this substring (the button will obey UILabel). For this I need subscript coordinates. I went through this, but I cannot understand it. Suppose my full line is abc, 567-324-6554, New York. I want 567-324-6554 to appear on the button for which I need its coordinates. How can I use the link above to find the substring coordinates? Thanks,

+6
source share
1 answer

UILabel has no methods for this. You can do this with a UITextView , since it implements the UITextInput protocol . You need to set the editable text view to NO .

Something like this unverified code should work:

 - (CGRect)rectInTextView:(UITextView *)textView stringRange:(CFRange)stringRange { UITextPosition *begin = [textView positionFromPosition:textView.beginningOfDocument offset:stringRange.location]; UITextPosition *end = [textView positionFromPosition:begin offset:stringRange.length]; UITextRange *textRange = [textView textRangeFromPosition:begin toPosition:end]; return [textView firstRectForRange:textRange]; } 

This should return a CGRect (in a text view coordinate system) that covers the substring specified by stringRange . You can set the button frame to this rectangle if you make a preview button for the text view.

If a substring spans multiple lines, the rectangle will cover only the first line.

+7
source

Source: https://habr.com/ru/post/908408/


All Articles