NSText字段添加行距



我使用 NSTextField 而不是 NSTextView 来接收用户输入,但我需要自定义字体和文本颜色和行距。我使用下面的代码,字体和颜色都可以,但我不知道如何设置行距。

[self.titleField setTextColor:textColor];
[self.titleField setFont:bold14];

我还使用 NSAttributedString 来解决这个问题:

NSFont *bold14 = [NSFont boldSystemFontOfSize:14.0];
NSColor *textColor = [NSColor redColor];
NSMutableParagraphStyle *textParagraph = [[NSMutableParagraphStyle alloc] init];
[textParagraph setLineSpacing:10.0];
NSDictionary *attrDic = [NSDictionary dictionaryWithObjectsAndKeys:bold14, NSFontAttributeName, textColor, NSForegroundColorAttributeName, textParagraph, NSParagraphStyleAttributeName, nil];
NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:title attributes:attrDic]; 
[self.titleField setAllowsEditingTextAttributes:YES];
[self.titleField setAttributedStringValue:attrString];

上面的代码可以显示属性字符串,但是当我删除文本字段中的字符串并开始输入时,单词没有任何属性。

如何在NSTextField中输入具有自定义字体,颜色和行距的字符串?

最好继续使用NSTextField's属性设置方法而不是NSAttributedString,因为这样它可以将设置发送到字段编辑器。每个文本字段都有一个NSTextView(大多数情况下)"字段编辑器";字段编辑器是进行编辑的。

您的NSAttributedString没有粘住,因为您只是告诉文本字段暂时显示该字符串。当字段编辑器弹出时,文本字段(单元格)会传递其自己的属性,如textField.fonttextField.textColor,但从不传递NSAttributedString的属性。

最好使用NSTextView才能使用-setDefaultParagraphStyle因为从我所看到的情况来看,您无论如何都要编辑多行。如果由于性能问题或其他原因而无法做到,则:


子类NSTextFieldCell,因为这是所有NSTextField工作和覆盖

- (NSText *)setUpFieldEditorAttributes:(NSText *)textObj

(在 NSCell 中声明)以您想要的方式为字段编辑器设置属性,以便您可以自己通过-setDefaultParagraphStyle(和字体等)向其发送行高值。(textObj是要设置的字段编辑器)。

最新更新