objective-c - NSTextView:以编程方式格式化文本

标签 objective-c swift cocoa nstextview

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

最佳答案

您可以使用 NSAttributedStringNSMutableAttributedString 只需指定文本格式(颜色、文本大小等)并将其传递给您的 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];

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

关于objective-c - NSTextView:以编程方式格式化文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32326802/

相关文章:

objective-c - 是否可以在 Linux 上运行的应用程序中使用 Cocoa 类

cocoa - NSEvent - NSLeftMouseDown

ios - 在 segues 之间切换 iOS 中的 UINavigationController 栏

ios - NSUserDefaults 在使用应用程序时保存并重新加载,但在应用程序重新启动时重置

swift - OSX Cocoa NSSearchField 清除按钮不响应点击

swift - 在 Swift 中使用 C 宏

swift - 无法在 Swift 中将文件传输/删除到 ~/Library/Application Scripts/

objective-c - 如何在 iOS 中使用数字通知 "bubble"?

objective-c - 您如何使用 ARC 处理 'require( ..., bail)' 语句?

cocoa - NSArray 上的 copyWithZone 是否也对其元素调用 copyWithZone ?