I'm trying to achieve a visual effect with a UITextView
whereby the text has a distinct background color, eg:
The approach I tried to build on was based on a code snippet from Apple used to calculate lines, and then built upon as shown in this example to calculate the frames of the lines, eg:
NSLayoutManager *layoutManager = [textView layoutManager];
NSString *string = textView.text;
NSInteger numberOfLines, index, stringLength = [string length];
NSMutableArray *ranges = [[NSMutableArray alloc] init];
NSMutableArray *frames = [[NSMutableArray alloc] init];
for (index = 0, numberOfLines = 0; index < stringLength; numberOfLines++)
{
NSRange tempRange;
NSRange range = [string lineRangeForRange:NSMakeRange(index, 0)];
CGRect rect = [layoutManager lineFragmentRectForGlyphAtIndex:index
effectiveRange:&tempRange];
[ranges addObject:[NSValue valueWithRange:range]];
[frames addObject:[NSValue valueWithCGRect:rect]];
NSMaxRange(tempRange);
}
Then I take the frames and draw the rectangles. This and similar approaches I've tried share the common problem that the frame's of lines I calculate contain the trailing white spaces, and I'm not sure how to trim them (and also maintain the correct flow of text).
I'm concerned I might be overthinking this. Is there a simpler way?