Last active
October 12, 2016 04:30
-
-
Save frankchang0125/3540abab2e75aacd50bc566a44554276 to your computer and use it in GitHub Desktop.
Calculate text height with given width and font
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
| /* 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
http://www.cnblogs.com/willbin/p/3955786.html
http://stackoverflow.com/questions/13621084/boundingrectwithsize-for-nsattributedstring-returning-wrong-size