Created
June 20, 2018 23:37
-
-
Save bricklife/9cd62bd86f472a21317add9229563bfa 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
// | |
// 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