You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift实现所有CollectionViewCell高度匹配内容最长单元格

Swift实现所有CollectionViewCell高度统一为最长内容单元格的高度

以下是完整Swift代码,实现UICollectionView中所有单元格高度统一匹配内容最长的单元格的动态高度:

自定义CollectionViewCell代码

import UIKit

class YourCustomCell: UICollectionViewCell {
    // 自动换行的文本标签
    let textLabel: UILabel = {
        let label = UILabel()
        label.numberOfLines = 0
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupUI()
    }
    
    private func setupUI() {
        contentView.addSubview(textLabel)
        // 设置标签与单元格的边距约束
        NSLayoutConstraint.activate([
            textLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 10),
            textLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -10),
            textLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 10),
            textLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -10)
        ])
    }
}

视图控制器代码

import UIKit

class YourViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {

    @IBOutlet weak var collectionView: UICollectionView!
    
    // 测试数据,包含不同长度的文本内容
    var data: [String] = [
        "Lorem Ipsum是印刷和排版行业的标准占位文本,常用于展示字体效果或版面布局。",
        "短文本",
        "这是一段用于测试的长文本,内容长度可变,用来验证单元格高度是否能统一匹配最长内容的高度。"
    ]
    
    private var cellHeights: [CGFloat] = []
    private var maxCellHeight: CGFloat = 0

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 注册自定义单元格
        collectionView.register(YourCustomCell.self, forCellWithReuseIdentifier: "cell")
        
        // 计算所有文本对应的高度,确定最大单元格高度
        calculateMaxCellHeight()
    }
    
    // 计算并获取最长内容对应的单元格高度
    private func calculateMaxCellHeight() {
        let cellContentWidth = collectionView.frame.width - 20 // 减去左右边距
        let textFont = UIFont.systemFont(ofSize: 17)
        
        for text in data {
            let height = heightForText(text, font: textFont, width: cellContentWidth)
            cellHeights.append(height)
        }
        
        // 取所有高度中的最大值,无数据时默认0
        maxCellHeight = cellHeights.max() ?? 0
        // 加上单元格上下边距的高度
        maxCellHeight += 20
    }

    // MARK: - UICollectionView数据源方法
    
    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: - UICollectionView布局代理方法
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        // 所有单元格使用统一的最大高度
        return CGSize(width: collectionView.frame.width, height: maxCellHeight)
    }
    
    // 计算文本在指定宽度和字体下的高度
    private func heightForText(_ text: String, font: UIFont, width: CGFloat) -> CGFloat {
        let maxSize = CGSize(width: width, height: .greatestFiniteMagnitude)
        let drawingOptions = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)
        let textAttributes = [NSAttributedString.Key.font: font]
        let textRect = NSString(string: text).boundingRect(with: maxSize, options: drawingOptions, attributes: textAttributes, context: nil)
        return ceil(textRect.height)
    }
}

关键说明

  • 自定义单元格中设置了文本标签自动换行,并通过约束保证内容有合适边距,避免内容被截断。
  • 在视图加载时预先计算所有文本的高度,取最大值作为所有单元格的统一高度,确保视觉一致性。
  • 使用boundingRect方法准确计算文本高度,结合ceil方法避免小数高度导致的布局问题。

内容的提问来源于stack exchange,提问作者dax tech

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 17:14:51