6 1*_*6 1 5 cocoa objective-c nstextfield nsattributedstring
我使用 NSTextField 而不是 NSTextView 来接收用户输入,但我需要自定义字体、文本颜色和行距。我使用下面的代码,字体和颜色都可以,但我不知道如何设置行距。
[self.titleField setTextColor:textColor];
[self.titleField setFont:bold14];
Run Code Online (Sandbox Code Playgroud)
我还使用 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];
Run Code Online (Sandbox Code Playgroud)
上面的代码可以显示属性字符串,但是当我删除文本字段中的字符串并开始输入时,这些单词没有任何属性。
如何在 NSTextField 中输入具有自定义字体、颜色和行距的字符串?
最好保留NSTextField's属性设置方法而不是 ,NSAttributedString因为这样它可以将设置发送到字段编辑器。每个文本字段都有一个NSTextView(大多数时候)“字段编辑器”;字段编辑器负责编辑。
您NSAttributedString没有坚持下去,因为您只是告诉文本字段暂时显示该字符串。当字段编辑器弹出时,文本字段(单元格)会传递自己的属性,例如textField.font和 ,textField.textColor但绝不会传递NSAttributedString的属性。
最好使用NSTextView能够使用的,-setDefaultParagraphStyle因为据我所知,您无论如何都在编辑多行。如果由于性能问题或其他原因而不能,那么:
Subclass NSTextFieldCell,因为这就是所有工作的作用NSTextField,并覆盖
- (NSText *)setUpFieldEditorAttributes:(NSText *)textObj
Run Code Online (Sandbox Code Playgroud)
(在 中声明NSCell)以您想要的方式为字段编辑器设置属性,以便您可以-setDefaultParagraphStyle自己通过(和字体等)向其发送行高值。(textObj是要设置的字段编辑器)。
| 归档时间: |
|
| 查看次数: |
2135 次 |
| 最近记录: |