Cocoa NSTextField 行距

9
我遇到了一个非常简单的问题,我有几个NSTextField(现在无法使用NSTextView),我需要更改显示文本的行间距。如何才能缩小行高或者行间距?缩小字体大小不是一个选项。
希望能得到任何帮助!
祝你周末愉快,
!)

7
为什么不能使用NSTextView?NSTextField通常用于单行文本字段。 - sidyll
3个回答

8
为了参考,您可以阅读这篇段落样式的描述:Cocoa段落样式,请注意其中的所有内容都是在行之间、段落之间、段落之前等添加的额外空间。您可以将NSMutableParagraphStyle中的值设置为零,但不能再低。
要进一步缩小行间距,请使用setMaximumLineHeight,感谢“6 1”提供的代码(我已经添加了setMaximumLineHeight):
NSString *title = @"title here";
NSFont *bold14 = [NSFont boldSystemFontOfSize:14.0];
NSColor *textColor = [NSColor redColor];
NSMutableParagraphStyle *textParagraph = [[NSMutableParagraphStyle alloc] init];
[textParagraph setLineSpacing:10.0];  // this sets the space BETWEEN lines to 10points
[textParagraph setMaximumLineHeight:12.0]; this sets the MAXIMUM height of the lines to 12points

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

3

Swift版本的Jason Harrison优秀的Obj-c答案:

let title:String = "title here"
let bold14:NSFont = NSFont.boldSystemFontOfSize(14.0)
let textColor:NSColor = NSColor.redColor()
let textParagraph:NSMutableParagraphStyle = NSMutableParagraphStyle()
textParagraph.lineSpacing = 10.0  /*this sets the space BETWEEN lines to 10points*/
textParagraph.maximumLineHeight = 12.0/*this sets the MAXIMUM height of the lines to 12points*/
let attribs = [NSFontAttributeName:bold14,NSForegroundColorAttributeName:textColor,NSParagraphStyleAttributeName:textParagraph]
let attrString:NSAttributedString = NSAttributedString.init(string: title, attributes: attribs)
textField.attributedStringValue = attrString

我希望文本在垂直方向上更加紧凑,但如果字体大小太小,文本将被框架裁剪。解决方法是将textField.bounds.origin.y值偏移几个像素。基本上:(font.size - leading) - Sentry.co

2
您可以使用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];

可以展示文本而非输入文本,只需设置行距即可。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接