ios – All CollectionViewCell top equal to largest cell label dynamic content material full code in swif

Spread the love

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

import UIKit

class YourViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {

@IBOutlet weak var collectionView: UICollectionView!

var information: [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() {

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

    // Calculate cell heights
    for textual content in information {
        let top = heightForText(textual content, font: UIFont.systemFont(ofSize: 17), width: collectionView.body.width - 20)

// MARK: - UICollectionViewDataSource

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection part: Int) -> Int {
    return information.rely

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

// MARK: - UICollectionViewDelegateFlowLayout

func collectionView(_ collectionView: UICollectionView, format collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let top = cellHeights[indexPath.item]
    return CGSize(width: collectionView.body.width, top: top)

// Perform to calculate the peak of the textual content
func heightForText(_ textual content: String, font: UIFont, width: CGFloat) -> CGFloat {
    let dimension = CGSize(width: width, top: .greatestFiniteMagnitude)
    let choices = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)
    let attributes = [NSAttributedString.Key.font: font]
    let rectangleHeight = NSString(string: textual content).boundingRect(with: dimension, choices: choices, attributes: attributes, context: nil).top
    return ceil(rectangleHeight)


Leave a Reply

Your email address will not be published. Required fields are marked *