设置UILabel行间距 [英] Set UILabel line spacing
问题描述
如何修改多行中的行之间的间隙 UILabel
?
How can I modify the gap between lines in a multiline UILabel
?
推荐答案
编辑:显然, NSAttributedString
会在iOS 6及更高版本上执行。而不是使用 NSString
设置标签的文本,创建一个 NSAttributedString
,设置属性,然后将其设置为标签上的 .attributedText
。你想要的代码将是这样:
Evidently NSAttributedString
will do it, on iOS 6 and later. Instead of using an NSString
to set the label's text, create an NSAttributedString
, set attributes on it, then set it as the .attributedText
on the label. The code you want will be something like this:
NSMutableAttributedString* attrString = [NSMutableAttributedString attributedStringWithString:@"Sample text"];
NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
[style setLineSpacing:24];
[attrString addAttribute:NSParagraphStyleAttributeName
value:style
range:NSMakeRange(0, strLength)];
uiLabel.attributedText = attrString;
由于历史原因,这里是我原来的答案:
For historical reasons, here's my original answer:
简短答案:您不能。要更改文本行之间的间距,您必须将 UILabel
子类化并滚动您自己的 drawTextInRect
,创建多个标签,或使用不同的字体(也许是为特定行高编辑的,请参阅Phillipe的答案)。
Short answer: you can't. To change the spacing between lines of text, you will have to subclass UILabel
and roll your own drawTextInRect
, create multiple labels, or use a different font (perhaps one edited for a specific line height, see Phillipe's answer).
长答案在线世界,文本行之间的空间被称为领先(具有标题的韵律,并且来自几十年前使用的铅金属)。 Leading是 UIFont
的只读属性,它在4.0中已弃用,并由 lineHeight
替代。据我所知,没有办法创建一个特定的参数集,如 lineHeight
;
Long answer: In the print and online world, the space between lines of text is known as "leading" (rhymes with 'heading', and comes from the lead metal used decades ago). Leading is a read-only property of UIFont
, which was deprecated in 4.0 and replaced by lineHeight
. As far as I know, there's no way to create a font with a specific set of parameters such as lineHeight
; you get the system fonts and any custom font you add, but can't tweak them once installed.
中没有空格参数UILabel
There is no spacing parameter in UILabel
, either.
我不是特别满意 UILabel
,所以我建议写你自己的子类或使用第三方库。这将使行为独立于您的字体选择,并且是最可重用的解决方案。
I'm not particularly happy with UILabel
's behavior as is, so I suggest writing your own subclass or using a 3rd-party library. That will make the behavior independent of your font choice and be the most reusable solution.
我希望 在 UILabel
,我很乐意证明错了!
I wish there was more flexibility in UILabel
, and I'd be happy to be proven wrong!
这篇关于设置UILabel行间距的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!