Created
June 14, 2017 07:07
-
-
Save vietstone-ng/80ba5047106018778e5d5e0eab942b43 to your computer and use it in GitHub Desktop.
This file contains 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
// | |
// SpacingLabel.swift | |
// SpacingLabel | |
// | |
// Created by Viet Nguyen Tran on 6/13/17. | |
// Copyright © 2017 iossimple. All rights reserved. | |
// | |
import UIKit | |
@IBDesignable | |
class SpacingLabel: UILabel { | |
@IBInspectable var lineHeight: CGFloat = 0 { | |
didSet { | |
updateSpacing() | |
} | |
} | |
@IBInspectable var letterSpacing: CGFloat = 0 { | |
didSet { | |
updateSpacing() | |
} | |
} | |
override var text: String? { | |
didSet { | |
updateSpacing() | |
} | |
} | |
func updateSpacing() { | |
if let text = self.text, text.characters.count != 0 { | |
let attributedString = NSMutableAttributedString(string: text) | |
let range = NSMakeRange(0, text.characters.count) | |
// default attributes | |
attributedString.addAttribute(NSFontAttributeName, value: self.font, range: range) | |
attributedString.addAttribute(NSForegroundColorAttributeName, value: self.textColor, range: range) | |
// lineHeight attribute | |
if lineHeight != 0 { | |
let paragraphStyle = NSMutableParagraphStyle() | |
paragraphStyle.minimumLineHeight = lineHeight | |
paragraphStyle.maximumLineHeight = lineHeight | |
paragraphStyle.alignment = self.textAlignment // alignment from UILabel | |
attributedString.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: range) | |
} | |
// letter Spacing | |
if letterSpacing != 0 { | |
attributedString.addAttribute(NSKernAttributeName, value: letterSpacing, range: range) | |
} | |
// show label | |
self.attributedText = attributedString | |
} else { | |
self.attributedText = nil | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment