关于如何格式化/颜色NSTextView的字符串的技术 [英] Technique on how to format/color NSTextView's string

查看:824
本文介绍了关于如何格式化/颜色NSTextView的字符串的技术的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个可靠的技术来做一个简单的字符串格式化(粗体,斜体,...)在NSTextView。文本解析几乎是用正则表达式完成的,但现在我需要应用字体trait,也更改大小。

I'm looking for a reliable technique to do simple string formatting(bold, italic,...) in a NSTextView. The text parsing is almost done with regex, but now I need to apply font trait and also change the size.

一些关于如何使文本粗体的代码片段

Some code snippets on how I make a text bold

[[textView textStorage] beginEditing];
[[textView textStorage] applyFontTraits:NSFontBoldTrait range:range];
[[textView textStorage] endEditing];

这个大小也随着

[[textView textStorage] beginEditing];  
NSFont* font = [[textView textStorage] attribute:NSFontAttributeName atIndex:range.location effectiveRange:nil];

NSFont* newFont = [NSFont fontWithName:[font familyName] 
                                  size:[font pointSize] + size];

[[textView textStorage] addAttribute:NSFontAttributeName 
                               value:newFont 
                               range:range];
[[textView textStorage] endEditing];

可以正常工作。我现在唯一的问题是,在某些情况下,当我键入新的字符,这些字符是粗体或斜体默认情况下,即使我不应用的属性。

works fine. The only problem I have now is that in some cases, when I type new characters, those characters are bold or italic by default, even though I don't apply the properties to them.

我必须使用 NSTextView setTypingAttributes $ c>

Do I have to reset something with the setTypingAttributes of the NSTextView or do I simply miss something here?

推荐答案

我认为你是正确的方法设置 typingAttributes 参考<-setTypingAttributes:

I think you are right with the approach to set typingAttributes. Reference for -setTypingAttributes: says


但是,如果添加任何更改文本属性的用户操作,操作应使用此方法以后应用这些属性。更改属性的用户操作应始终设置键入属性,因为在下一次输入之前可能没有后续选择更改。

However, if you add any user actions that change text attributes, the action should use this method to apply those attributes afterwards. User actions that change attributes should always set the typing attributes because there might not be a subsequent change in selection before the next typing.

似乎适用于您的情况。

我不知道所描述的行为是否只对像TextEdit这样的WYSIWYG编辑器正确。你似乎在工作的行为类似于一个编辑器的语法高亮。在那里,你从来没有真正想手动更改文本属性,而是从语法结构。它可能不适合在这种情况下,你应该重置 typingAttributes 或根据解析设置它到那里。

I don't know if the described behaviour is only correct for WYSIWYG editors like TextEdit. You seem to work on something that is similar in behaviour to an editor with syntax highlighting. There you never really want to change text attributes manually, but rather on structure from a grammar. It probably doesn't fit in that case, and you should reset typingAttributes or set it according to parsing up to there.

这篇关于关于如何格式化/颜色NSTextView的字符串的技术的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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