UILabel 内的 lineSpacing 属性无法按预期工作 [英] lineSpacing property inside UILabel doesn't work as expected
问题描述
我正在尝试创建一个自定义 UILabel
类,这将允许我增加 UILabel 上的行间距.我知道您可以在 IB 中使用属性文本字符串执行此操作,但是如果您使用自定义字体,则它不起作用.这是我的课程代码:
I am trying to create a custom UILabel
class which will allow me to increase the line spacing on a UILabel. I know you can do this in IB with an attributed text string, however it doesn't work if you are using custom fonts. Here is my class code:
import UIKit
@IBDesignable
class SpacingLabel: UILabel
{
@IBInspectable var lineSpacing: CGFloat = 10.0
override func awakeFromNib()
{
self.renderText()
}
override func prepareForInterfaceBuilder()
{
super.prepareForInterfaceBuilder()
self.renderText()
}
func renderText()
{
var attrString = NSMutableAttributedString(string:self.text!)
if font != nil
{
NSMutableParagraphStyle.defaultParagraphStyle().mutableCopy()
var paragraphStyle = NSMutableParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle
paragraphStyle.textAlignment = self.textAlignment
paragraphStyle.lineSpacing = self.lineSpacing
paragraphStyle.paragraphSpacing = self.lineSpacing
attrString.addAttributes([NSFontAttributeName : self.font!, NSParagraphStyleAttributeName : paragraphStyle], range: NSMakeRange(0, attrString.length))
self.attributedText = attrString
}
self.needsUpdateConstraints()
}
}
这是它在 IB(故事板)中的呈现方式:
This is how it renders in IB (Storyboard):
这是它在模拟器中的呈现方式:
And here's how it renders in the simulator:
我已经尝试添加 minimumLineHeight
和/或 maximumLineHeight
属性,但这些似乎在其他方面搞砸了...
I've tried adding minimumLineHeight
and/or maximumLineHeight
properties, but these just seem to mess it up in other ways...
推荐答案
所以...结果是 lineSpacing
属性在某种程度上与 UILabel 中的一个可能的私有变量/属性发生冲突代码>.我将我的属性重命名为
leading
,现在它可以完美运行.
So... It turned out that the property lineSpacing
is somehow clashing with a possible private variable/property within UILabel
. I renamed my property to leading
and now it works perfectly.
这篇关于UILabel 内的 lineSpacing 属性无法按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!