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

问题描述 投票:0回答:1

所有 CollectionViewCell 高度等于最大单元格标签动态内容 swif 完整代码

导入UIKit

类 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)
}

}

ios swift uicollectionview height uicollectionviewcell
1个回答
0
投票
let height = cellHeights.max()
return CGSize(width:collectionView.frame.width, height: height)

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

© www.soinside.com 2019 - 2024. All rights reserved.