Skip to content

Instantly share code, notes, and snippets.

@bricklife
Created June 20, 2018 23:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bricklife/9cd62bd86f472a21317add9229563bfa to your computer and use it in GitHub Desktop.
Save bricklife/9cd62bd86f472a21317add9229563bfa to your computer and use it in GitHub Desktop.
//
// LineHeightLabel.swift
// LineHeightLabel
//
// Created by Shinichiro Oba on 20/06/2018.
// Copyright © 2018 bricklife.com. All rights reserved.
//
import UIKit
class LineHeightLabel: UILabel {
private var _lineHeight: CGFloat = 0.0
var lineHeight: CGFloat {
set {
_lineHeight = newValue
update()
}
get {
return max(font.lineHeight, _lineHeight)
}
}
override var text: String? { didSet { update() } }
override var font: UIFont! { didSet { update() } }
override var textColor: UIColor! { didSet { update() } }
override var textAlignment: NSTextAlignment { didSet { update() } }
private func update() {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = lineHeight - font.lineHeight
paragraphStyle.alignment = textAlignment
var attr = [NSAttributedStringKey : Any]()
attr[.font] = font
attr[.foregroundColor] = textColor
attr[.paragraphStyle] = paragraphStyle
attributedText = text.flatMap { NSAttributedString(string: $0, attributes: attr) }
}
override var intrinsicContentSize: CGSize {
var size = super.intrinsicContentSize
let lineHeight = ceil(self.lineHeight * 2) / 2
let numOflines = ceil(size.height / lineHeight)
size.height = lineHeight * numOflines
return size
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment