macos NSMutableAttributedStrings - objectAtIndex:effectiveRange:: 越界
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11571948/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
NSMutableAttributedStrings - objectAtIndex:effectiveRange:: Out of bounds
提问by 425nesp
I'm trying to add some fancy text to a label, but I've run into some problems with the NSMutableAttributedString class. I was trying to achieve four this: 1. Change font, 2. Underline range, 3. Change range color, 4. Superscript range.
我正在尝试向标签添加一些花哨的文本,但我遇到了 NSMutableAttributedString 类的一些问题。我试图实现四个:1. 更改字体,2. 下划线范围,3. 更改范围颜色,4. 上标范围。
This code:
这段代码:
- (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];
}
Gives me this error:
给我这个错误:
NSMutableRLEArray objectAtIndex:effectiveRange:: Out of bounds
Also, I tried messing around with the ranges, but became even more confused when I tried NSRange worldRange = NSMakeRange(4, 5);
. I don't understand why that produces this: Hell^o wor^ld!
, where the letters inside the ^s are superscripts.
此外,我尝试弄乱范围,但当我尝试时变得更加困惑NSRange worldRange = NSMakeRange(4, 5);
。我不明白为什么会产生这个:Hell^o wor^ld!
,其中 ^s 中的字母是上标。
NSRange worldRange = NSMakeRange(6, 6);
produces the desired effect, hello ^world!^
.
NSRange worldRange = NSMakeRange(6, 6);
产生预期的效果,hello ^world!^
。
What the label looks like:
标签的样子:
回答by borrrden
Your length is too long on worldRange. NSMakeRange takes two arguments, the start point and the length, not the start point and the end point. That's probably why you are getting confused about both problems.
您在 worldRange 上的长度太长。NSMakeRange 有两个参数,起点和长度,而不是起点和终点。这可能就是您对这两个问题感到困惑的原因。
回答by Sherman Lo
NSRange
has two values, the start index and the length of the range.
NSRange
有两个值,起始索引和范围的长度。
So if you're starting at index 6 and going length
characters after that you're going past the end of the string, what you want is:
因此,如果您从索引 6 开始并在此length
之后的字符越过字符串的末尾,那么您想要的是:
NSRange worldRange = NSMakeRange(6, length - 6);