【问题标题】:NSTextView: format text programmaticallyNSTextView:以编程方式格式化文本
【发布时间】:2015-09-01 08:20:05
【问题描述】:

如何以编程方式格式化 NSTextView 中的部分文本?例如,将所有出现的单词“foo”设为蓝色,或者将所有文本设为灰色,但当前段落(光标所在的位置)为纯黑色? 谢谢

【问题讨论】:

标签: objective-c swift cocoa nstextview


【解决方案1】:

您可以使用NSAttributedString 或NSMutableAttributedString 只需指定文本格式(颜色、文本大小等)并将其传递给您的NSTextView,例如:

    NSString *str = @"test string";
    NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString: str];
    NSDictionary *attributes = @{
                                 NSForegroundColorAttributeName : [NSColor redColor],
                                 NSFontAttributeName : [NSFont fontWithName:@"HelveticaNeue-Bold" size:12.0]
                                 };
    [attrString setAttributes:attributes range:NSMakeRange(0, str.length)];

    [[self.myNSTextView textStorage] appendAttributedString: attrString];

这会将您的所有文本设置为相同,但只需将 range 属性替换为您只想更改这部分文本的属性: NSMakeRange(0, 2) 这只会将文本属性添加到前两个 lerrer。

【讨论】:

    猜你喜欢
    • 2013-01-16
    • 2010-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-08
    • 2015-04-20
    相关资源
    最近更新 更多