Last active
May 30, 2018 12:15
-
-
Save michaelevensen/38f675952eefed1b6f99722480c76df4 to your computer and use it in GitHub Desktop.
Adds Designable UILabel `Tracking` and `Line Height` for UILabel.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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