我正在尝试向标签添加一些花哨的文本,但我遇到了 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!^
。
标签的样子:
最佳答案
您在 worldRange 上的长度太长。 NSMakeRange 有两个参数,起点和长度,而不是起点和终点。这可能就是您对这两个问题感到困惑的原因。
关于objective-c - NSMutableAttributedStrings - objectAtIndex:effectiveRange::Out of bounds,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11571948/