Skip to content

Instantly share code, notes, and snippets.

@richardwei6
Created November 5, 2020 07:23
Show Gist options
  • Save richardwei6/50ee9a65f1fc86828132f6f115efbe32 to your computer and use it in GitHub Desktop.
Save richardwei6/50ee9a65f1fc86828132f6f115efbe32 to your computer and use it in GitHub Desktop.
extension String {
func getHeight(withConstrainedWidth width: CGFloat, font: UIFont) -> CGFloat {
let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: font], context: nil)
return ceil(boundingBox.height)
}
func getWidth(withConstrainedHeight height: CGFloat, font: UIFont) -> CGFloat {
let constraintRect = CGSize(width: .greatestFiniteMagnitude, height: height)
let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: font], context: nil)
return ceil(boundingBox.width)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment