线条之间显示NSAttributedString高亮/背景颜色(丑陋)

ste*_*vel 13 macos cocoa nstextview nsattributedstring core-text

我正在尝试很好地显示NSTextView中突出显示的段落.现在,我是通过创建一个背景颜色的NSAttributedString来做到这一点的.这是一些简化的代码:

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];
Run Code Online (Sandbox Code Playgroud)

这种方法基本上有效,因为它产生突出显示的文本.

单线单排

不幸的是,当存在多条线时,除了线本身之外,高光覆盖线之间的垂直空间,导致丑陋.

多行双倍间隔文本

有谁知道在Cocoa中进行这种突出显示的方法?下面的图片基本上就是我要找的东西(忽略白框上的阴影):

白色文字

我愿意使用CoreText,html或任何必要的东西来使事情看起来更好.

Hus*_*bir 0

尝试这个:-

     -(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];

        }
     }
}
Run Code Online (Sandbox Code Playgroud)