NSMutableAttributedStrings-objectAtIndex:effectiveRange ::越界 [英] NSMutableAttributedStrings - objectAtIndex:effectiveRange:: Out of bounds

查看:205
本文介绍了NSMutableAttributedStrings-objectAtIndex:effectiveRange ::越界的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试向标签中添加一些精美的文本,但是NSMutableAttributedString类遇到了一些问题.我试图实现以下四个目标:1.更改字体,2.下划线范围,3.更改范围颜色,4.上标范围.

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.

此代码:

- (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内的字母是上标.

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(6, 6);产生所需的效果,hello ^world!^.

标签的外观:

What the label looks like:

推荐答案

在worldRange上,您的长度太长. NSMakeRange接受两个参数,即起点和 length ,而不是起点和终点.这可能就是为什么您对这两个问题感到困惑的原因.

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.

这篇关于NSMutableAttributedStrings-objectAtIndex:effectiveRange ::越界的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆