Skip to content

Instantly share code, notes, and snippets.

@scspijker
Created November 1, 2019 11:07
Show Gist options
  • Save scspijker/55625e4a3a58acee0d5514234f898c9b to your computer and use it in GitHub Desktop.
Save scspijker/55625e4a3a58acee0d5514234f898c9b to your computer and use it in GitHub Desktop.
@IBDesignable
public class UILabelWithLineHeight: UILabel {
override public var intrinsicContentSize: CGSize {
var size = intrinsicContentSizeWithoutPadding
let numberOfLines = Int(ceil(size.height / font.lineHeight))
let padding = (lineHeightMultiple - 1.0) * font.lineHeight
size.height += CGFloat(numberOfLines - 1) * padding
return size
}
override public var text: String? {
didSet {
updateAttributedText()
}
}
@IBInspectable public var lineHeightMultiple: CGFloat = 1.0 {
didSet {
updateAttributedText()
}
}
private var intrinsicContentSizeWithoutPadding: CGSize {
let maxSize = CGSize(width: frame.size.width, height: CGFloat(MAXFLOAT))
let text = (self.text ?? "") as NSString
return text.boundingRect(with: maxSize, options: .usesLineFragmentOrigin, attributes: [.font: font], context: nil).size
}
private func updateAttributedText() {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineHeightMultiple = lineHeightMultiple
attributedText = NSAttributedString(string: text ?? "", attributes: [
.font: font,
.paragraphStyle: paragraphStyle,
.foregroundColor: textColor
])
invalidateIntrinsicContentSize()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment