2013-09-22 118 views
12

我想很好地显示在NSTextView突出显示的段落。现在,我通过创建具有背景颜色的NSAttributedString来完成此操作。这里有一些简化的代码: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]; 

这种方法基本上起作用,因为它产生突出显示的文本。

Single line single spaced

不幸的是,当存在多行,高亮覆盖垂直空间之间的线路,除了线本身,从而导致丑陋。

Multi line double spaced text

有谁知道的方式做这种可可突出的?下面的图片基本上就是我要找的(忽略了白框的阴影):

whiteout text

我很愿意使用CoreText,HTML,或一切必要的努力使事情看起来更好。

+2

你有没有解决这个问题,我有完全相同的问题 – user499846

+1

我没有真正弄清楚这一点,但我弄清楚如何至少围绕文本居中选择直方图,以便它不是全部以上或下面。它涉及计算'[paragraphStyle setLineSpacing:xx]'和'[paragraphStyle setLineHeightMultiple:xx]',使它们相同。再次,这并没有解决实际问题,只是让它更容易被接受。 – stevel

回答

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 *[email protected]"\n"; 
      NSAttributedString *attr=[[NSAttributedString alloc]initWithString:str]; 
      [tv .textStorage appendAttributedString:attr]; 
      isNext=NO; 
     } 
     if (isNext==YES) 
     { 
      NSString *[email protected]"\n"; 
      NSAttributedString *attr=[[NSAttributedString alloc]initWithString:str]; 
      [tv .textStorage appendAttributedString:attr]; 

     } 
    } 
} 
+0

不幸的是,在这种情况下,行不会被\ n字符分隔 - 这是一个段落,所以文本会自动换行。不过,谢谢你的尝试。 – stevel

+0

我修改了代码。请现在尝试,也不会弄脏这些词。 –

2

您将需要继承NSLayoutManager并重写:

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

这是绘制背景色矩形的原始方法。

+1

你如何实现这个方法,将会特定于你的应用程序。但是,作为附加的上下文,我用 ' - (void)enumerateLineFragmentsForGlyphRange:(NSRange)glyphRange usingBlock:(void(^)(CGRect rect,CGRect usedRect,NSTextContainer * textContainer,NSRange glyphRange,BOOL * stop))block' 创建一个CGRect结构数组,描述字符字形使用的边界,并与rectArray内容创建交点来限制我的高光边界。 – nzeltzer