NSAttributedString highlight/background color show

2020-03-01 07:08发布

问题:

I'm trying to nicely display paragraphs of highlighted in a NSTextView. Right now, I'm doing this by creating a NSAttributedString with a background color. Here's some simplified code:

NSDictionary *attributes = @{NSBackgroundColorAttributeName:NSColor.greenColor};
NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:@"Here is a single line of text with single spacing" attributes:attributes];

[textView.textStorage setAttributedString:attrString];

This approach basically works, in that it produces highlighted text.

Unfortunately, when multiple lines exist, the highlight covers the vertical space between the lines in addition to the lines themselves, resulting in ugliness.

Does anyone know of a way to do this kind of highlighting in Cocoa? The picture below is basically what I'm looking for (ignore the shadow on the white boxes):

I'd be willing to use CoreText, html, or whatever is necessary to make things look nicer.

回答1:

You will need to subclass NSLayoutManager and override:

- (void)fillBackgroundRectArray:(const CGRect *)rectArray
                      count:(NSUInteger)rectCount
          forCharacterRange:(NSRange)charRange
                      color:(UIColor *)color;

This is the primitive method for drawing background color rectangles.



回答2:

Try this:-

     -(IBAction)chooseOnlylines:(id)sender
{

 NSString *allTheText =[tv string];
    NSArray *lines = [allTheText componentsSeparatedByString:@"\n"];
    NSString *str=[[NSString alloc]init];
    NSMutableAttributedString *attr;
    BOOL isNext=YES;
    [tv setString:@""];
    for (str in lines)
    {
        attr=[[NSMutableAttributedString alloc]initWithString:str];
        if ([str length] > 0)
        {

        NSRange range=NSMakeRange(0, [str length]);
        [attr addAttribute:NSBackgroundColorAttributeName value:[NSColor greenColor] range:range];
        [tv .textStorage appendAttributedString:attr];
            isNext=YES;
        }
        else
        {
            NSString *str=@"\n";
            NSAttributedString *attr=[[NSAttributedString alloc]initWithString:str];
            [tv .textStorage appendAttributedString:attr];
            isNext=NO;
        }
        if (isNext==YES)
        {
            NSString *str=@"\n";
            NSAttributedString *attr=[[NSAttributedString alloc]initWithString:str];
            [tv .textStorage appendAttributedString:attr];

        }
     }
}