Skip to content

Instantly share code, notes, and snippets.

@garethng
Created September 29, 2022 02:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save garethng/b6771f6bfb08e18a16e38213071a0f7b to your computer and use it in GitHub Desktop.
Save garethng/b6771f6bfb08e18a16e38213071a0f7b to your computer and use it in GitHub Desktop.
Extension String to calculate the width and height of a label based on the string length
extension String {
func height(withConstrainedWidth width: CGFloat, font: UIFont) -> CGFloat {
let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)
return ceil(boundingBox.height)
}
func width(withConstrainedHeight height: CGFloat, font: UIFont) -> CGFloat {
let constraintRect = CGSize(width: .greatestFiniteMagnitude, height: height)
let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: 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