-> get dynamic height and width of your content in swift.
First Of all copy and paste this extension.
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: [NSAttributedString.Key.font: 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: [NSAttributedString.Key.font: font], context: nil)
return ceil(boundingBox.width)
}
}
How to use this
let str = "I want to test"
let Strheight = str.height(withConstrainedWidth: self.view.frame.width, font: UIFont.systemFont(ofSize: 16))
OR you can get content with and height without extension in swift
let size = str.size(withAttributes: [NSAttributedString.Key.font : UIFont(name: "SFProDisplay-Regular", size: 16)])
print(size.height)