Reputation: 61
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,
Upvotes: 6
Views: 3557
Reputation: 385620
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.
Upvotes: 7