Created
May 13, 2019 13:59
-
-
Save yuraist/202d94acd3dac976ae0ce3680a0a3c6e to your computer and use it in GitHub Desktop.
Swift String type extension for a height and width estimation
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
extension String { | |
func height(withConstraintWidth width: CGFloat, font: UIFont = UIFont.systemFont(ofSize: 17)) -> 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 width(withConstraintHeight height: CGFloat, font: UIFont = UIFont.systemFont(ofSize: 17)) -> 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