How do I locate the CGRect for a substring of text in a UILabel?


For a given NSRange, I’d like to find a CGRect in a UILabel that corresponds to the glyphs of that NSRange. For example, I’d like to find the CGRect that contains the word “dog” in the sentence “The quick brown fox jumps over the lazy dog.”

Visual description of problem

The trick is, the UILabel has multiple lines, and the text is really attributedText, so it’s a bit tough to find the exact position of the string.

The method that I’d like to write on my UILabel subclass would look something like this:

 - (CGRect)rectForSubstringWithRange:(NSRange)range;

Details, for those who are interested:

My goal with this is to be able to create a new UILabel with the exact appearance and position of the UILabel, that I can then animate. I’ve got the rest figured out, but it’s this step in particular that’s holding me back at the moment.

What I’ve done to try and solve the issue so far:

  • I’d hoped that with iOS 7, there’d be a bit of Text Kit that would solve this problem, but most every example I’ve seen with Text Kit focuses on UITextView and UITextField, rather than UILabel.
  • I’ve seen another question on Stack Overflow here that promises to solve the problem, but the accepted answer is over two years old, and the code doesn’t perform well with attributed text.

I’d bet that the right answer to this involves one of the following:

  • Using a standard Text Kit method to solve this problem in a single line of code. I’d bet it would involve NSLayoutManager and textContainerForGlyphAtIndex:effectiveRange
  • Writing a complex method that breaks the UILabel into lines, and finds the rect of a glyph within a line, likely using Core Text methods. My current best bet is to take apart @mattt’s excellent TTTAttributedLabel, which has a method that finds a glyph at a point – if I invert that, and find the point for a glyph, that might work.

Update: Here’s a github gist with the three things I’ve tried so far to solve this issue:

Source: Ios7 Questions

Categorised as ios, ios7, textkit, uilabel Tagged , , ,


Leave a Reply

Your email address will not be published. Required fields are marked *

Still Have Questions?

Our dedicated development team is here for you!

We can help you find answers to your question for as low as 5$.

Contact Us