Skip to content

Instantly share code, notes, and snippets.

@michaelevensen
Last active May 30, 2018 12:15
Show Gist options
  • Save michaelevensen/38f675952eefed1b6f99722480c76df4 to your computer and use it in GitHub Desktop.
Save michaelevensen/38f675952eefed1b6f99722480c76df4 to your computer and use it in GitHub Desktop.
Adds Designable UILabel `Tracking` and `Line Height` for UILabel.
@IBDesignable
class DesignableLabel: UILabel {
// Tracking
@IBInspectable var tracking: CGFloat = 0.0 {
didSet {
if attributedText?.length == nil { return }
let attrStr = NSMutableAttributedString(attributedString: attributedText!)
let range = NSMakeRange(0, attributedText!.length)
attrStr.addAttributes([.kern: tracking], range: range)
attributedText = attrStr
}
}
// Line Height
@IBInspectable var lineHeight: CGFloat = 20 {
didSet {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.minimumLineHeight = lineHeight
paragraphStyle.maximumLineHeight = lineHeight
paragraphStyle.alignment = self.textAlignment
// Take into account tracking (if already set)
var attrString: NSMutableAttributedString = NSMutableAttributedString(string: text!)
if let existingAttributedText = attributedText {
attrString = existingAttributedText.makeStringWith(text: text!)
}
attrString.addAttribute(NSAttributedStringKey.font, value: font, range: NSRange(location: 0, length: attrString.length))
attrString.addAttribute(NSAttributedStringKey.paragraphStyle, value: paragraphStyle, range: NSRange(location: 0, length: attrString.length))
attributedText = attrString
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment