Skip to content

Instantly share code, notes, and snippets.

@anngdev
Created May 31, 2023 08:32
Show Gist options
  • Save anngdev/89cd89dfd3e12501d290851341b1af14 to your computer and use it in GitHub Desktop.
Save anngdev/89cd89dfd3e12501d290851341b1af14 to your computer and use it in GitHub Desktop.
Swift heightForAttributedString
//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