2

I am basically creating a custom attribute to draw a rounded rectangle in my text subclassing NSLayoutManager with drawGlyphsForGlyphRange method below. Below works like a charm with ranges that spans one line. However, when the range of text spans in two lines, I am getting a big rectangle which draws the attribute along those two lines. I think I should be using a different approach here, I tried nsbackgroundattribute to draw the highlight but unfortunately I cannot make the highlight rounded rect using that.

I would appreciate any directions.

-(void)drawGlyphsForGlyphRange:(NSRange)glyphsToShow atPoint:(CGPoint)origin {

NSTextStorage *textStorage = self.textStorage;
NSRange glyphRange = glyphsToShow;
while (glyphRange.length > 0) {
   NSRange charRange = [self characterRangeForGlyphRange:glyphRange actualGlyphRange:NULL], attributeCharRange, attributeGlyphRange;
   id attribute = [textStorage attribute:IKSpecialHighlightAttributeName atIndex:charRange.location longestEffectiveRange:&attributeCharRange inRange:charRange];

    attributeGlyphRange = [self glyphRangeForCharacterRange:attributeCharRange actualCharacterRange:NULL];

    attributeGlyphRange = NSIntersectionRange(attributeGlyphRange, glyphRange);

    if( attribute != nil ) {



        NSTextContainer *textContainer = self.textContainers[0];

        CGRect boundingRect = [self boundingRectForGlyphRange:attributeGlyphRange inTextContainer:textContainer];





        [[UIColor colorWithRed:221.0/255.0 green:255.0/255.0 blue:0.0/255.0 alpha:1] setFill]; // set rounded rect's bg color



        boundingRect.origin.x += origin.x-3.0;

        boundingRect.origin.y += origin.y+3.0;

        boundingRect.size.width += 6.0;



        UIBezierPath *roundedRect = [UIBezierPath bezierPathWithRoundedRect:boundingRect cornerRadius: 3.0];



        [roundedRect fillWithBlendMode: kCGBlendModeNormal alpha:1.0f];




        [super drawGlyphsForGlyphRange:attributeGlyphRange atPoint:origin];

    }

    else {

        [super drawGlyphsForGlyphRange:glyphsToShow atPoint:origin];

    }

    glyphRange.length = NSMaxRange(glyphRange) - NSMaxRange(attributeGlyphRange);

    glyphRange.location = NSMaxRange(attributeGlyphRange);

}

}

ilteris
  • 457
  • 1
  • 7
  • 21
  • Part of the solution is here: http://stackoverflow.com/questions/20694942/drawing-a-calayer-over-text-in-a-uitextview-which-spans-multiple-lines. I basically use the layoutManager methods -enumerateLineFragmentsForGlyphRange:usingBlock: and enumerateEnclosingRectsForGlyphRange:withinSelectedGlyphRange:inTextContainer:usingBlock: to cycle through lines, and get the location in view of the text. Having some issues though. – Myron Slaw Dec 20 '13 at 03:36

0 Answers0