Last active
December 21, 2017 15:58
-
-
Save idrougge/3ebe18ecde2399cb102416f3b65d7a8c to your computer and use it in GitHub Desktop.
Calculate minimum width for UILabel for better headlines
This file contains hidden or 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
extension UILabel { | |
/// Minimum width fitting text in alotted number of lines | |
var minimumWidth:CGFloat { | |
get { | |
guard intrinsicContentSize.width >= bounds.width || intrinsicContentSize.height >= ceil(font.lineHeight) * CGFloat(numberOfLines) | |
else { return intrinsicContentSize.width } | |
let rect = self.textRect(forBounds: CGRect.init(origin: .zero, size: CGSize(width: bounds.width, height: .infinity)), limitedToNumberOfLines: self.numberOfLines) | |
return calculateWidth(0 ..< rect.width, height: rect.height) | |
} | |
} | |
private func calculateWidth(_ range:Range<CGFloat>, height maxHeight:CGFloat = .infinity) -> CGFloat { | |
guard range.upperBound - range.lowerBound > 10 else { return ceil(range.upperBound) } | |
let pivot = range.lowerBound + (range.upperBound - range.lowerBound) / 2 | |
let box = self.textRect(forBounds: CGRect(origin: .zero, size: CGSize(width: pivot, height: maxHeight)), limitedToNumberOfLines: 0) | |
if box.minY < 0 { return calculateWidth(pivot ..< range.upperBound, height: maxHeight) } | |
else { return calculateWidth(range.lowerBound ..< pivot, height: maxHeight) } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment