4

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

[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 中输入具有自定义字体、颜色和行距的字符串?

4

1 回答 1

4

最好使用NSTextField's属性设置方法而不是 an,NSAttributedString因为这样它可以将设置发送到字段编辑器。每个文本字段都有一个NSTextView(大部分时间)“字段编辑器”;字段编辑器是在做编辑。

NSAttributedString没有坚持,因为你只是告诉文本字段暂时显示那个字符串。当字段编辑器弹出文本字段(单元格)时,它会传递它自己的属性textField.fonttextField.textColor但绝不会传递NSAttributedString's 属性。

最好使用 anNSTextView以便能够使用-setDefaultParagraphStyle,因为据我所见,无论如何您都在编辑多行。如果由于性能问题或其他原因不能,那么:


Subclass NSTextFieldCell,因为这就是所有的NSTextField工作,并覆盖

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

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

于 2012-06-25T06:03:33.953 回答