简体   繁体   中英

NSTextField add line spacing

I use NSTextField not NSTextView to receive the user input, but I need to custom the font and textColor and line spacing. I use the code below, it's ok for font and color but I don't know how to set a line spacing.

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

And I also use a NSAttributedString to solve the problem:

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];

the code above is ok to show a attributed string, but when I delete the string in the textfield and start to input, the words come without any attribute.

How can I input a string in NSTextField with custom font, color and line spacing?

It's best to stay with NSTextField's attribute setting methods instead of an NSAttributedString because then it can send the settings to the field editor. Every text field has an NSTextView (most of the time) " Field Editor "; and the field editor is what is doing the editing.

Your NSAttributedString isn't sticking because you're only telling the textfield to temporarily display that one string. When the field editor pops up the text field (cell) passes on its own attributes like textField.font and textField.textColor but never the NSAttributedString 's attributes.

It would be best to use an NSTextView to be able to use -setDefaultParagraphStyle because you're editing multiple lines anyways, from what I see. If you can't, because of performance problems or something else, then:


Subclass NSTextFieldCell , because that's what does all the NSTextField work, and override

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

(declared in NSCell ) to set up attributes for your field editor the way you want it, so you can send it a line height value through -setDefaultParagraphStyle (and font etc.) yourself. ( textObj is the field editor to be set up).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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