2011-12-02 100 views
5

我掙扎着一個非常簡單的問題,我有幾個NSTextField(我現在不能使用NSTextView),我需要改變顯示文本的行間距。 我可以做些什麼來減少行高或行間距?縮小字號不是一個選項。可可NSTextField行間距

任何幫助將非常感謝!

有一個偉大的週末,

!)

+7

爲什麼不能使用NSTextView? NSTextField通常用於單行文本字段。 – sidyll

回答

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

可以顯示不是用於輸入文字的文字。而且我只知道如何設置行間距。

+0

謝謝。它爲我工作。 – Sid

3

爲了便於參考,您需要閱讀對段落樣式的描述:Cocoa Paragraph Styles並注意在那裏的所有內容都在行之間,段落之間,段落之前添加了額外的空間。您可以將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

斯威夫特版本賈森·哈里森的出色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 
+0

我希望文字在垂直方向更加緊湊,但是如果我按照字體大小寫下文本,文本會被框架剪切。解決方法是用幾個像素來抵消textField.bounds.origin.y值。基本上:(font.size - leading) – eonist