自动化 UICollectionViewCell 的宽度大小 - Swift

Automate width size of UICollectionViewCell - Swift

如何 UICollectionViewCell 自动设置 width 尺码基本尺码 string

您可以这样做来计算字符串的宽度

let padding = 30

func collectionView(_ collectionView: UICollectionView,
                    layout collectionViewLayout: UICollectionViewLayout,
                    sizeForItemAt indexPath: IndexPath) -> CGSize {
    let lbl = UILabel() 
    lbl.text = arr[indexPath.item] // arr = [String]()
    let si = lbl.sizeThatFits(CGSize(width:CGFloat.greatestFiniteMagnitude, height:40)) 
    print(si.width)
    return CGSize(width:si.width + padding , height:40)
}

class VCName:UIViewController , UICollectionViewDelegate  , UICollectionViewDataSource , UICollectionViewDelegateFlowLayout { }