简体   繁体   English

如何在光标处设置字体?

[英]How do I set the font at cursor?

I have a NSTextView and I want to set the font at the cursor (cursor: insertion point cursor, the flashing bar) , meaning at the cursor, the font becomes Times New Roman (example). 我有一个NSTextView,我想在光标处设置字体(光标:插入点光标,闪烁的条),这意味着在光标处,字体变为Times New Roman(示例)。 Wherever the cursor is at, I want the font to change. 无论光标位于何处,我都希望更改字体。 I tried doing 我试着做

[self.textView.textStorage addAttributes:@{NSFontAttributeName: [NSFont fontWithName:@"Times New Roman" size:14]} range:NSMakeRange([[[self.textView selectedRanges] objectAtIndex:0] rangeValue].location, 0)];

But it was not working. 但这没有用。 Is there another way? 还有另一种方法吗? I tried a number of things, and I still have problems. 我尝试了很多事情,但仍然有问题。

First, it would be helpful to avoid confusion between "cursor" as in the mouse cursor (eg pointing arrow or I-beam) and, what I assume you mean, "cursor" as in insertion point or selection. 首先,避免鼠标光标中的“光标”(例如,指向箭头或工字梁)与插入点或选择中的“光标”之间的混淆是有帮助的。

The attributes that will be used for newly-typed text are stored in the text view's typingAttributes property. 将用于新键入的文本的属性存储在文本视图的typingAttributes属性中。 So, you would do: 因此,您将执行以下操作:

NSMutableDictionary* attributes = [textView.typingAttributes mutableCopy];
attributes[NSFontAttributeName] = [NSFont fontWithName:@"Times New Roman" size:14];
self.textView.typingAttributes = attributes;

Of course, if there's a selection, you would usually want to change the font in all of the selected ranges in addition to setting the typing attributes. 当然,如果有选择,通常除了设置键入属性外,您还希望在所有选定范围内更改字体。 You would use rangesForUserCharacterAttributeChange for that. 您将为此使用rangesForUserCharacterAttributeChange

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM