Last active
February 23, 2023 08:38
-
-
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.
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
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) | |
} |
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 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