425*_*esp 11 macos objective-c 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];
}
Run Code Online (Sandbox Code Playgroud)
给我这个错误:
NSMutableRLEArray objectAtIndex:effectiveRange:: Out of bounds
Run Code Online (Sandbox Code Playgroud)
此外,我尝试搞乱范围,但当我尝试时变得更加困惑NSRange worldRange = NSMakeRange(4, 5);.我不明白为什么产生这个:Hell^o wor^ld!,^ s中的字母是上标.
NSRange worldRange = NSMakeRange(6, 6);产生预期的效果,hello ^world!^.
标签看起来像什么:

NSRange 有两个值,起始索引和范围的长度.
因此,如果你从索引6开始并且length在那之后去了字符你将超过字符串的结尾,你想要的是:
NSRange worldRange = NSMakeRange(6, length - 6);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12521 次 |
| 最近记录: |