Created
November 26, 2015 15:02
-
-
Save firefightingcode/844c0a5c20f25eb9c48f to your computer and use it in GitHub Desktop.
An extension for UILabel to set text with specific kerning, line spacing or line height multiple
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
import UIKit | |
extension UILabel { | |
func setText(text: String, withKerning kerning: Double) { | |
self.attributedText = NSAttributedString(string: text, attributes: kerningAttribute(kerning)) | |
} | |
func setText(text: String, withLineSpacing lineSpacing: CGFloat) { | |
self.attributedText = NSAttributedString(string: text, attributes: lineSpacingAttribute(lineSpacing)) | |
} | |
func setText(text: String, withLineHeightMultiple lineHeightMultiple: CGFloat) { | |
self.attributedText = NSAttributedString(string: text, attributes:lineHeightMultipleAttribute(lineHeightMultiple)) | |
} | |
func setText(text: String, withKerning kerning: Double, lineSpacing: CGFloat) { | |
var attributes = kerningAttribute(kerning) | |
attributes.add(lineSpacingAttribute(lineSpacing)) | |
self.attributedText = NSAttributedString(string: text, attributes: attributes) | |
} | |
func setText(text: String, withKerning kerning: Double, lineHeightMultiple: CGFloat) { | |
var attributes = kerningAttribute(kerning) | |
attributes.add(lineHeightMultipleAttribute(lineHeightMultiple)) | |
self.attributedText = NSAttributedString(string: text, attributes: attributes) | |
} | |
private func kerningAttribute(kerning: Double) -> [String: AnyObject] { | |
return [NSKernAttributeName: kerning] | |
} | |
private func lineSpacingAttribute(lineSpacing: CGFloat) -> [String: AnyObject] { | |
let paragraphStyle = NSMutableParagraphStyle() | |
paragraphStyle.lineSpacing = lineSpacing | |
return [NSParagraphStyleAttributeName : paragraphStyle] | |
} | |
private func lineHeightMultipleAttribute(lineHeightMultiple: CGFloat) -> [String: AnyObject] { | |
let paragraphStyle = NSMutableParagraphStyle() | |
paragraphStyle.lineHeightMultiple = lineHeightMultiple | |
return [NSParagraphStyleAttributeName : paragraphStyle] | |
} | |
} | |
private extension Dictionary { | |
mutating func add(dictionary: Dictionary) { | |
for (name, value) in dictionary { | |
self[name] = value | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment