All CollectionViewCell height equal to largest cell label dynamic content in swift

45 Views Asked by At

All CollectionViewCell height equal to largest cell label dynamic content full code in swif

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

}

1

There are 1 best solutions below

0
Mykyta iOS On
let height = cellHeights.max()
return CGSize(width:collectionView.frame.width, height: height)

Rewrite your delegate method to get max cell height instead of selecting one by index.