Created
March 31, 2017 09:42
-
-
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
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
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