Skip to content

Instantly share code, notes, and snippets.

@cwalo
Created June 7, 2019 03:31
Show Gist options
  • Save cwalo/9b8c4ad06eaf001fb062ad6458752d4b to your computer and use it in GitHub Desktop.
Save cwalo/9b8c4ad06eaf001fb062ad6458752d4b to your computer and use it in GitHub Desktop.
How to calculate the height of a string fitting a given width
func heightOfString(_ string: String, attributes: [NSAttributedString.Key: Any], fitting width: CGFloat) -> CGFloat {
let constraintRect = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude)
let boundingRect = string.boundingRect(with: constraintRect,
options: [.usesLineFragmentOrigin, .usesFontLeading],
attributes: attributes,
context: nil)
return boundingRect.size.height
}
func heightOfAttributedString(_ attributedString: NSAttributedString, fitting width: CGFloat) -> CGFloat {
let constraintRect = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude)
let boundingRect = attributedString.boundingRect(with: constraintRect,
options: [.usesLineFragmentOrigin, .usesFontLeading],
context: nil)
return boundingRect.size.height
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment