Skip to content

Instantly share code, notes, and snippets.

@wtshm
Created January 23, 2018 10:05
Show Gist options
  • Save wtshm/6155dfe105c871e3f7e9d7a22199b6ab to your computer and use it in GitHub Desktop.
Save wtshm/6155dfe105c871e3f7e9d7a22199b6ab to your computer and use it in GitHub Desktop.
import UIKit
extension UILabel {
@IBInspectable var kerning: Float {
get {
var range = NSMakeRange(0, (text ?? "").characters.count)
guard let kern = attributedText?.attribute(NSKernAttributeName, at: 0, effectiveRange: &range), let value = kern as? NSNumber else {
return 0
}
return value.floatValue
}
set {
var attrs: NSMutableAttributedString
if let attributedText = attributedText {
attrs = NSMutableAttributedString(attributedString: attributedText)
} else if let text = text {
attrs = NSMutableAttributedString(string: text)
} else {
attrs = NSMutableAttributedString(string: "")
}
let range = NSMakeRange(0, attrs.length)
attrs.addAttribute(NSKernAttributeName, value: NSNumber(value: newValue), range: range)
self.attributedText = attrs
}
}
@IBInspectable var lineHeight: Float {
get {
return self.lineHeight
}
set {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 1.0
paragraphStyle.lineHeightMultiple = CGFloat(newValue)
paragraphStyle.alignment = self.textAlignment
let attrString = NSMutableAttributedString(string: self.text!)
attrString.addAttribute(NSFontAttributeName, value: self.font, range: NSMakeRange(0, attrString.length))
attrString.addAttribute(NSParagraphStyleAttributeName, value:paragraphStyle, range:NSMakeRange(0, attrString.length))
self.attributedText = attrString
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment