I have a string coming from server which I am displaying on UILabel multiligne. It is within that string, I am identifying some particular substring. I want to place a button on that substring(button will be a subview of UILabel). For this I require substring coordinates. I went through this but I am not able to understand it. Suppose my complete string is abc, 567-324-6554, New York. I want 567-324-6554 to be displayed on button for which I need its coordinates. How can I use above link to find coordinates of substring? Thanks,
UILabel
doesn't have any methods for doing this. You can do it with UITextView
, because it implements the UITextInput
protocol. You will want to set the text view's editable
property to NO
.
Something like this untested 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];
}
That should return a CGRect
(in the text view's coordinate system) that covers the substring specified by stringRange
. You can set the button's frame to this rectangle, if you make the button a subview of the text view.
If the substring spans multiple lines, the rectangle will only cover the first line.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With