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.
source share