Objective c NSMutableAttributedStrings-objectAtIndex:effectiveRange::越界
我试图向标签中添加一些奇特的文本,但NSMutableAttributedString类遇到了一些问题。我试图做到这四点:1。改变字体,2。下划线范围,3。改变范围颜色,4。上标范围 此代码:Objective c NSMutableAttributedStrings-objectAtIndex:effectiveRange::越界,objective-c,macos,nsattributedstring,nsrange,Objective C,Macos,Nsattributedstring,Nsrange,我试图向标签中添加一些奇特的文本,但NSMutableAttributedString类遇到了一些问题。我试图做到这四点:1。改变字体,2。下划线范围,3。改变范围颜色,4。上标范围 此代码: - (void)applicationDidFinishLaunching:(NSNotification*)aNotification { NSMutableAttributedString* display = [[NSMutableAttributedString alloc]
- (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)代码>产生想要的效果,你好^world^代码>
标签的外观:
NSRange
有两个值,起始索引和范围长度
因此,如果从索引6开始,然后是长度
个字符,然后是字符串的末尾,那么您需要的是:
NSRange worldRange = NSMakeRange(6, length - 6);
你的长度在worldRange上太长了。NSMakeRange接受两个参数,起点和长度,而不是起点和终点。这可能就是您对这两个问题感到困惑的原因。是的!你说得对。我一直在尝试使用它,就像使用子字符串方法一样!啊,新手的错误。