Skip to content

Instantly share code, notes, and snippets.

@fuxingloh
Last active February 23, 2023 08:38
Show Gist options
  • Save fuxingloh/82623f0ac0461727c1ef2ec78bdfde68 to your computer and use it in GitHub Desktop.
Save fuxingloh/82623f0ac0461727c1ef2ec78bdfde68 to your computer and use it in GitHub Desktop.
iOS Swift: How to count the width of the UILabel. And how to size UICollectionViewCell dynamically with label.
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let text = collections[indexPath.row].name
let width = UILabel.textWidth(font: titleFont, text: text)
return CGSize(width: width + left + right, height: height)
}
extension UILabel {
func textWidth() -> CGFloat {
return UILabel.textWidth(label: self)
}
class func textWidth(label: UILabel) -> CGFloat {
return textWidth(label: label, text: label.text!)
}
class func textWidth(label: UILabel, text: String) -> CGFloat {
return textWidth(font: label.font, text: text)
}
class func textWidth(font: UIFont, text: String) -> CGFloat {
let myText = text as NSString
let rect = CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)
let labelSize = myText.boundingRect(with: rect, options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)
return ceil(labelSize.width)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment