如何设置“隐藏”的NSAttributedString中文本的属性? [英] How can I set a "hidden" attribute for text inside NSAttributedString?

查看:105
本文介绍了如何设置“隐藏”的NSAttributedString中文本的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有 NSTextView 控件的可可应用,该控件将其文本保存在 NSAttributedString 中(实际上,我相信它是 NSMutableAttributedString )。我可以轻松地在字符串内的不同字符范围上设置和修改不同的文本属性(如字体,下划线等)。

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.

但是,我想设置一部分文字为隐藏(类似于CSS属性 display:none 的效果)。当发生外部事件时(例如单击了一个按钮),我想取消隐藏或隐藏该特定范围的字符。

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.

无论如何,都可以使用 NSAttributedString

Is there anyway to do this with NSAttributedString?

推荐答案

另一种可能性是在想要的文本上使用自定义属性隐藏,然后在 NSAttributedString 上的类别中编写您自己的方法,该方法将创建一个新的属性字符串,该字符串将排除标记为隐藏的文本。

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:我完全是在脑海中写下了这个,不保证可以编译,工作,点燃硬盘驱动器,不踢狗等等。

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.

这篇关于如何设置“隐藏”的NSAttributedString中文本的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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