Swift中所有CollectionViewCell高度等于最大单元格标签动态内容

rn0zuynd  于 12个月前  发布在  Swift
关注(0)|答案(1)|浏览(120)

所有CollectionViewCell高度等于最大单元格标签动态内容Swif中的完整代码
导入UIKit
class YourViewController:UIViewController、UICollectionViewDataSource、UICollectionViewDelegate、UICollectionViewDelegateFlowLayout {

@IBOutlet weak var collectionView: UICollectionView!

var data: [String] = ["Lorem Ipsum is simply dummy text of the printing and typesetting industry.", "Short text", "Another long text for testing purposes. This can be of variable length depending on the data."]

var cellHeights: [CGFloat] = []

override func viewDidLoad() {
    super.viewDidLoad()

    // Register your custom cell
    collectionView.register(YourCustomCell.self, forCellWithReuseIdentifier: "cell")

    // Calculate cell heights
    for text in data {
        let height = heightForText(text, font: UIFont.systemFont(ofSize: 17), width: collectionView.frame.width - 20)
        cellHeights.append(height)
    }
}

// MARK: - UICollectionViewDataSource

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return data.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! YourCustomCell
    cell.textLabel.text = data[indexPath.item]
    return cell
}

// MARK: - UICollectionViewDelegateFlowLayout

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let height = cellHeights[indexPath.item]
    return CGSize(width: collectionView.frame.width, height: height)
}

// Function to calculate the height of the text
func heightForText(_ text: String, font: UIFont, width: CGFloat) -> CGFloat {
    let size = CGSize(width: width, height: .greatestFiniteMagnitude)
    let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)
    let attributes = [NSAttributedString.Key.font: font]
    let rectangleHeight = NSString(string: text).boundingRect(with: size, options: options, attributes: attributes, context: nil).height
    return ceil(rectangleHeight)
}

}

ru9i0ody

ru9i0ody1#

let height = cellHeights.max()
return CGSize(width:collectionView.frame.width, height: height)

重写委托方法以获取最大单元格高度,而不是通过索引选择一个。

相关问题