Skip to content

Instantly share code, notes, and snippets.

@idrougge
Last active December 21, 2017 15:58
Show Gist options
  • Save idrougge/3ebe18ecde2399cb102416f3b65d7a8c to your computer and use it in GitHub Desktop.
Save idrougge/3ebe18ecde2399cb102416f3b65d7a8c to your computer and use it in GitHub Desktop.
Calculate minimum width for UILabel for better headlines
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