Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSMutableAttributedStrings - objectAtIndex:effectiveRange:: Out of bounds

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.

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(6, 6); produces the desired effect, hello ^world!^.

What the label looks like:
outputtedText

like image 801
425nesp Avatar asked Jul 20 '12 02:07

425nesp


1 Answers

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.

like image 191
borrrden Avatar answered Sep 18 '22 18:09

borrrden