R – How to set a “hidden” attribute for text inside NSAttributedString

cocoansattributedstringobjective-c

I have a Cocoa app with an NSTextView control which holds its text in an NSAttributedString (actually I believe it's a NSMutableAttributedString). I can easily set and modify different text attributes (such as font, underline, etc.) on different character ranges inside that string.

However, I want to set a part of the text as hidden (similar to the effect of the CSS attribute display: none). When an external event occurs (say a button clicked), I want to unhide or hide that specific range of characters.

Is there anyway to do this with NSAttributedString?

Best Solution

Another possibility would be to use a custom attribute on the text you want to hide, and then write your own method in a category on NSAttributedString that creates a new attributed string that excludes the text marked as hidden.

- (NSAttributedString *)attributedStringWithoutHiddenText {
    NSMutableAttributedString *result = [[[NSMutableString alloc] init] autorelease];
    NSRange fullRange = NSMakeRange(0, [self length]);
    NSRange range = NSZeroRange;
    while (NSMaxRange(range) < [self length]) {
        NSDictionary *attributes = [self attributesAtIndex:range.location longestEffectiveRange:&range inRange:fullRange];
        if ([[attributes objectForKey:MyHiddenTextAttribute] boolValue])
            continue;

        NSAttributedString *substring = [[NSAttributedString alloc] initWithString:[[self string] substringWithRange:range] attributes:attributes];
        [result appendAttributedString:substring];
        [substring release];
    }
    return result;
}

Caveat: I totally just wrote this off the top of my head, and it's not guaranteed to compile, work, light your hard drive on fire, not kick your dog, etc.

This would generate a string that's appropriate for drawing, but you would still need the original string for accessing any of the hidden text. Depending on the size of your strings, this could be a big memory overhead.