Created
May 31, 2023 08:32
-
-
Save anngdev/89cd89dfd3e12501d290851341b1af14 to your computer and use it in GitHub Desktop.
Swift heightForAttributedString
This file contains hidden or 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
//For UIlabel | |
func heightForAttributedString(_ attributedString: NSAttributedString, width: CGFloat) -> CGFloat { | |
let maxSize = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude) | |
let options: NSStringDrawingOptions = [.usesLineFragmentOrigin, .usesFontLeading] | |
let boundingRect = attributedString.boundingRect(with: maxSize, options: options, context: nil) | |
let height = ceil(boundingRect.height) | |
return height | |
} | |
//Or | |
func heightForAttributedString(_ attributedString: NSAttributedString, width: CGFloat) -> CGFloat { | |
let label = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: CGFloat.greatestFiniteMagnitude)) | |
label.attributedText = attributedString | |
label.numberOfLines = 0 | |
label.sizeToFit() | |
return label.frame.height | |
} | |
//For UITextview | |
func heightForAttributedString(_ attributedString: NSAttributedString, width: CGFloat) -> CGFloat { | |
let textView = UITextView(frame: CGRect(x: 0, y: 0, width: width, height: CGFloat.greatestFiniteMagnitude)) | |
textView.attributedText = attributedString | |
let fixedWidth = width | |
let newSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude)) | |
return newSize.height | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment