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()
}
}
This is how it renders in IB (Storyboard):
And here's how it renders in the simulator:
I've tried adding minimumLineHeight
and/or maximumLineHeight
properties, but these just seem to mess it up in other ways...
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.