Skip to content

Instantly share code, notes, and snippets.

@philosopherdog
Last active December 10, 2021 20:47
Show Gist options
  • Save philosopherdog/a3cb82ece60b115cf75fcb421eedcab0 to your computer and use it in GitHub Desktop.
Save philosopherdog/a3cb82ece60b115cf75fcb421eedcab0 to your computer and use it in GitHub Desktop.
String Dimension Provider
//
// StringDimensionProvider.swift
//
// Created by steve on 2019-07-11.
// Copyright © 2019 Steven Thompson. All rights reserved.
//
//
// StringHeightProvider.swift
//
// Created by steve on 2019-07-11.
// Copyright © 2019 Steven Thompson. All rights reserved.
//
import UIKit
final class StringDimensionProvider {
static let shared = StringDimensionProvider()
private init() { }
private let label = UILabel()
func computeHeight(
with text: String?,
font: UIFont,
maxWidth: CGFloat,
maxLineCount: Int = 1
) -> CGFloat {
if text.isEmptyOrNil { return 0 }
label.text = text
label.font = font
label.preferredMaxLayoutWidth = maxWidth
label.numberOfLines = maxLineCount
return label.intrinsicContentSize.height
}
func computeHeight(
with attributedText: NSAttributedString?,
maxWidth: CGFloat = .infinity,
numberOfLines: Int = 1
) -> CGFloat {
if attributedText.isEmptyOrNil { return 0 }
label.attributedText = attributedText
label.preferredMaxLayoutWidth = maxWidth
label.numberOfLines = numberOfLines
return label.intrinsicContentSize.height
}
func computeSize(
with attributedText: NSAttributedString?,
maxWidth: CGFloat = .infinity,
numberOfLines: Int = 1
) -> CGSize {
if attributedText.isEmptyOrNil { return .zero }
label.numberOfLines = numberOfLines
label.attributedText = attributedText
label.preferredMaxLayoutWidth = maxWidth
return .init(
width: label.intrinsicContentSize.width,
height: label.intrinsicContentSize.height
)
}
func computeHeight(
with attributedList: [(NSAttributedString?, Int)],
maxWidth: CGFloat
) -> CGFloat {
var result: CGFloat = 0
attributedList.forEach { arg in
let (str, numberOfLines) = arg
result += computeHeight(
with: str,
maxWidth: maxWidth,
numberOfLines: numberOfLines
)
}
return result
}
func isTruncated(
with attributedText: NSAttributedString?,
maxWidth: CGFloat,
numberOfLines: Int = 1
) -> Bool {
let containedHeight = computeHeight(
with: attributedText,
maxWidth: maxWidth,
numberOfLines: numberOfLines
)
let uncontainedHeight = computeHeight(
with: attributedText,
maxWidth: maxWidth,
numberOfLines: .zero
)
return uncontainedHeight > containedHeight
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment