【问题标题】:NSMutableAttributedStrings - objectAtIndex:effectiveRange:: Out of boundsNSMutableAttributedStrings - objectAtIndex:effectiveRange:: 越界
【发布时间】:2012-07-19 07:02:23
【问题描述】:

我正在尝试向标签添加一些花哨的文本,但我遇到了 NSMutableAttributedString 类的一些问题。我试图实现四个:1.更改字体,2.下划线范围,3.更改范围颜色,4.上标范围。

这段代码:

- (void)applicationDidFinishLaunching:(NSNotification*)aNotification
{
    NSMutableAttributedString* display = [[NSMutableAttributedString alloc]
                                          initWithString:@"Hello world!"];
    NSUInteger length = [[display string]length] - 1;

    NSRange wholeRange = NSMakeRange(0, length);
    NSRange helloRange = NSMakeRange(0, 4);
    NSRange worldRange = NSMakeRange(6, length);

    NSFont* monoSpaced = [NSFont fontWithName:@"Menlo" 
                                         size:22.0];

    [display addAttribute:NSFontAttributeName
                    value:monoSpaced
                    range:wholeRange];

    [display addAttribute:NSUnderlineStyleAttributeName 
                    value:[NSNumber numberWithInt:1] 
                    range:helloRange];

    [display addAttribute:NSForegroundColorAttributeName 
                    value:[NSColor greenColor]
                    range:helloRange];

    [display addAttribute:NSSuperscriptAttributeName 
                    value:[NSNumber numberWithInt:1] 
                    range:worldRange];

    //@synthesize textLabel; is in this file.
    [textLabel setAttributedStringValue:display];
}

给我这个错误:

NSMutableRLEArray objectAtIndex:effectiveRange:: Out of bounds

另外,我尝试弄乱范围,但当我尝试NSRange worldRange = NSMakeRange(4, 5); 时变得更加困惑。我不明白为什么会这样:Hell^o wor^ld!,其中 ^s 内的字母是上标。

NSRange worldRange = NSMakeRange(6, 6); 产生所需的效果,hello ^world!^

标签是什么样子的:

【问题讨论】:

    标签: objective-c macos nsattributedstring nsrange


    【解决方案1】:

    NSRange 有两个值,开始索引和范围的长度。

    因此,如果您从索引 6 开始并在之后使用 length 字符,那么您将超过字符串的末尾,您想要的是:

    NSRange worldRange = NSMakeRange(6, length - 6);
    

    【讨论】:

      【解决方案2】:

      您在 worldRange 上的长度过长。 NSMakeRange 有两个参数,起点和长度,而不是起点和终点。这可能就是您对这两个问题感到困惑的原因。

      【讨论】:

      • 是的!你说得对。我一直在尝试像子字符串方法一样使用它!啊,菜鸟的错误。
      猜你喜欢
      • 2013-10-21
      • 1970-01-01
      • 1970-01-01
      • 2014-05-31
      • 1970-01-01
      • 1970-01-01
      • 2012-10-28
      • 2013-12-15
      相关资源
      最近更新 更多