如何使用 Swift 为 UICollectionView 创建动态宽度和静态高度



我正在使用customcell实现UICollection视图。在这里,我需要根据customcell标签字符串创建动态宽度,staticHeight需要设置。在这里,我为不知道静态高度dynamicwidth使用了下面的代码。如何实现这一点?

extension ViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return (items[indexPath.row] as String).size(withAttributes: nil)
//return CGSize(width: label.frame.width, height: 33.5)
}
}

根据要在label中添加text计算collectionViewCell'swidth

假设itemsStringarray

extension ViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let textWidth = items[indexPath.row].size(withAttributes:[.font: UIFont.systemFont(ofSize: 20.0)]).width + 30.0 //30.0 is the extra padding
let width = min(textWidth, 100.0) //100.0 is the max width
return CGSize(width: width, height: collectionView.bounds.height)
}
}

根据您的要求添加attributesheight

最新更新