Skip to content

Instantly share code, notes, and snippets.

@sanghapark
Created March 31, 2017 09:42
Show Gist options
  • Save sanghapark/43bb1e820d19bc44a2550f1521872a06 to your computer and use it in GitHub Desktop.
Save sanghapark/43bb1e820d19bc44a2550f1521872a06 to your computer and use it in GitHub Desktop.
[iOS] figure out UITextView's height based on a given string with value
func calculateTextViewHeight(inset: UIEdgeInsets, lineFragmentPadding: CGFloat = 5.0, maxWidth: CGFloat, text: String, font: UIFont) -> CGSize {
let widthWithoutInset = maxWidth - (inset.left + inset.right + (2 * lineFragmentPadding))
let contraintRect = CGSize(width: widthWithoutInset, height: CGFloat.max)
let style = NSMutableParagraphStyle()
style.lineBreakMode = .ByWordWrapping
let attributes = [NSFontAttributeName: font, NSParagraphStyleAttributeName: style]
let boudingBox = NSString(string: text).boundingRectWithSize(contraintRect, options: .UsesLineFragmentOrigin, attributes: attributes, context: nil)
let newWidth = (boudingBox.size.width + (inset.left + inset.right + (2 * lineFragmentPadding) + 0.25)).roundNearest(0.5)
let newHeight = (boudingBox.size.height + ((inset.top + inset.bottom) + 0.25)).roundNearest(0.5)
return CGSize(width: newWidth, height: newHeight)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment