Created
June 7, 2019 03:31
-
-
Save cwalo/9b8c4ad06eaf001fb062ad6458752d4b to your computer and use it in GitHub Desktop.
How to calculate the height of a string fitting a given width
This file contains 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 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