cocoa - NSTextView 和 NSAttributedString

标签 cocoa nstextview nsattributedstring

我试图将属性字符串粘贴到我的 NSTextView 中,但它只是显示为纯文本,没有属性。我像这样创建了我的字符串:

    NSString *str = @"Parsing Directory Structure\n\n";

NSMutableAttributedString *attrstr = [[NSMutableAttributedString alloc] initWithString:str];
NSDictionary *attributes = @{
                             NSForegroundColorAttributeName : [NSColor blueColor],
                             NSFontAttributeName : [NSFont fontWithName:@"HelveticaNeue-Bold" size:20.f]
                             };
[attrstr setAttributes:attributes range:NSRangeFromString(str)];

[[self.textView textStorage] appendAttributedString:attrstr];

在 NSTextView( ScrollView 内)上,我仍然选中“允许富文本”框,并且未选中“可编辑”框。我基本上尝试像控制台输出窗口一样使用它。

最佳答案

NSMakeRangeFromString 解析范围的文本表示,它不会创建覆盖字符串的范围。由于您的文本不包含整数,因此它返回范围 {0, 0} - 位置和长度均为零。因此,您的文本没有样式。

替换为NSMakeRange(0, str.length),您的代码应该可以工作。

关于cocoa - NSTextView 和 NSAttributedString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17682559/

相关文章:

swift - acceptsFirstMouse 在 macOS 上点击

objective-c - NSSlider NSSliderCell 裁剪自定义旋钮

cocoa - 当使用 NSTextFieldDelegate 时 - 控制 :textView:doCommandBySelector: how do we allow/make normal performance of e. g。退格键?

ios - NSString.sizeWithAttributes 支持的属性键列表?

xcode - 非事件窗口上带有自定义图像的 Mac 圆形纹理按钮

cocoa - 如何禁用 NSTextView 的自动换行?

objective-c - 如何破坏 NSTextView 的 "smart"复制和粘贴,它添加了不需要的空格?

macos - 设置 NSTextView 的占位符字符串

ios - 打开设置为 UILabel 作为属性字符串的文本上的链接。从 json 响应中读取属性字符串

swift - 设置前景色仅对 NSAttributedString 有效一次