2

I'm trying to achieve a visual effect with a UITextView whereby the text has a distinct background color, eg:

Example Text Effect

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?

Community
  • 1
  • 1
isaac
  • 4,867
  • 1
  • 21
  • 31
  • Here's a downloadable example project that might help you: https://github.com/mattneub/Programming-iOS-Book-Examples/blob/master/iOS7bookExamples/bk2ch10p543drawingWithTextKit/ch23p815attributedStringDrawing3/StyledText.m It draws a box around the tapped line, eliminating the whitespace (return character) at the end. It isn't quite as sophisticated as what you're trying to do, but it might help. – matt Jan 20 '17 at 17:07
  • Is this the original code? `index` is untouched and `NSMaxRange`'s return value is not used. However, you get the layout glyphs range in `tempRange`. Simply have a look at the string, if there are whitespaces, remove them and re-layout the (partial) string. (BTW: Glyphs and characters does not necessarily have a 1-to-1 relationship.) – Amin Negm-Awad Jan 20 '17 at 20:39
  • Did you figure it out? – Joseph Francis Dec 09 '17 at 00:31

0 Answers0