objective-c - NSMutableAttributedStrings - objectAtIndex:effectiveRange::Out of bounds

标签 objective-c macos nsattributedstring nsrange

我正在尝试向标签添加一些花哨的文本,但我遇到了 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!^

标签的样子:
outputtedText

最佳答案

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

关于objective-c - NSMutableAttributedStrings - objectAtIndex:effectiveRange::Out of bounds,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11571948/

相关文章:

ios - 为什么 NSAttributedString 不继承 NSString ? NSAttributedString 的父类是 NSObject 为什么?

ios - 如何向文本包含 NSBackgroundColorAttributeName 的 UILabel 添加填充

ios - 首次使用应用程序的徒步旅行

objective-c - 如何找到 os x 上所有事件窗口的根元素

python - libmysqlclient_r.18.dylib 与/usr/local/mysql/lib/MacOS 不同

macos - 更改窗口背景的 Alpha,而不是整个窗口

java - 在线免费 OPC 服务器用于测试和调试

objective-c - DetailView 不从 UITableViewController 按下打开(iOS Xcode)

iphone - UITableView 滚动时 UITableViewCell 上的数据丢失?

objective-c - 如何阻止时间 UILabel 在每次增量时调整大小?