Skip to content

Instantly share code, notes, and snippets.

@vibrazy
Last active February 9, 2016 23:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vibrazy/40d5ee3c2b19d267323a to your computer and use it in GitHub Desktop.
Save vibrazy/40d5ee3c2b19d267323a to your computer and use it in GitHub Desktop.
Sweet UILabel extension for Line Height and Paragraph Height
//
// UILabel+Paragraph.swift
//
// Created by Daniel Tavares on 09/02/2016.
// Copyright © 2016 Daniel Tavares. All rights reserved.
//
import Foundation
//MARK: - Associated Value Struct
//https://wezzard.com/2015/10/09/associated-object-and-swift-struct/
public final class Associated<T>: NSObject, NSCopying {
public typealias Type = T
public let value: Type
public init(_ value: Type) { self.value = value }
public func copyWithZone(zone: NSZone) -> AnyObject {
return self.dynamicType.init(value)
}
}
extension Associated where T: NSCopying {
public func copyWithZone(zone: NSZone) -> AnyObject {
return self.dynamicType.init(value.copyWithZone(zone) as! Type)
}
}
//MARK: - Line Options Extension
private var LineOptionsKey = "LineOptions"
struct LineOptions {
let height: CGFloat
let paragraphHeight: CGFloat
}
@IBDesignable extension UILabel {
@IBInspectable var lineOptions: LineOptions? {
get {
return (objc_getAssociatedObject(self, &LineOptionsKey) as? Associated<LineOptions>).map{$0.value}
}
set {
let value = newValue.map{ Associated<LineOptions>($0) }
objc_setAssociatedObject(self, &LineOptionsKey, value,.OBJC_ASSOCIATION_RETAIN)
setText(text, lineOptions: value?.value)
}
}
func setText(text: String?, lineOptions: LineOptions?) {
guard let text = text, lineOptions = lineOptions else { return }
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = lineOptions.height
paragraphStyle.paragraphSpacing = lineOptions.paragraphHeight
let attributedText = NSMutableAttributedString(string: text)
attributedText.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: NSMakeRange(0, attributedText.length))
self.attributedText = attributedText
}
}
/* - Usage
let lineOptions = LineOptions(height: 10, paragraphHeight: 16)
label.setText(description, lineOptions: lineOptions)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment