最佳答案
它在下面的答案中有解释。
HorizontalCollectionView Content width and spacing
用关联字体计算字符串的大小。
extension String {
func size(with font: UIFont) -> CGSize {
let fontAttribute = [NSAttributedString.Key.font: font]
let size = self.size(withAttributes: fontAttribute)
return size
}
}
在 collectionView(_, collectionViewLayout:_, sizeForItemAt)
中返回计算出的宽度和 collectionView 的高度。
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let newWidth = titles[indexPath.row].size(with: labelFont!).width + 10 //Added 10 to make the label visibility very clear
return CGSize(width: newWidth, height: collectionView.bounds.height)
}
关于ios - 如何根据文本使 UICollectioncell 宽度动态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53520998/