Skip to content

Instantly share code, notes, and snippets.

@frankchang0125
Last active October 12, 2016 04:30
Show Gist options
  • Save frankchang0125/3540abab2e75aacd50bc566a44554276 to your computer and use it in GitHub Desktop.
Save frankchang0125/3540abab2e75aacd50bc566a44554276 to your computer and use it in GitHub Desktop.
Calculate text height with given width and font
/* Get the height of ONE line text with given width and font */
func heightOfOneLineString(text: String, width: CGFloat, font: UIFont) -> CGFloat {
let rectOneLine = NSString(string: text).boundingRect(with: CGSize(width: width, height: CGFloat(MAXFLOAT)),
options: .truncatesLastVisibleLine,
attributes: [ NSFontAttributeName: font ],
context: nil)
return rectOneLine.size.height
}
/* Get the height of MULTIPLE lines text with given width and font */
func heightOfMultipleLinesString(text: String, width: CGFloat, font: UIFont) -> CGFloat {
let rectMultipleLines = NSString(string: text).boundingRect(with: CGSize(width: width, height: CGFloat(MAXFLOAT)),
options: .usesLineFragmentOrigin,
attributes: [ NSFontAttributeName: font ],
context: nil)
return rectMultipleLines.size.height
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment