All CollectionViewCell peak 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 knowledge: [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() {
tremendous.viewDidLoad()
// Register your customized cell
collectionView.register(YourCustomCell.self, forCellWithReuseIdentifier: "cell")
// Calculate cell heights
for textual content in knowledge {
let peak = heightForText(textual content, font: UIFont.systemFont(ofSize: 17), width: collectionView.body.width - 20)
cellHeights.append(peak)
}
}
// MARK: - UICollectionViewDataSource
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection part: Int) -> Int {
return knowledge.depend
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! YourCustomCell
cell.textLabel.textual content = knowledge[indexPath.item]
return cell
}
// MARK: - UICollectionViewDelegateFlowLayout
func collectionView(_ collectionView: UICollectionView, structure collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let peak = cellHeights[indexPath.item]
return CGSize(width: collectionView.body.width, peak: peak)
}
// Perform to calculate the peak of the textual content
func heightForText(_ textual content: String, font: UIFont, width: CGFloat) -> CGFloat {
let dimension = CGSize(width: width, peak: .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).peak
return ceil(rectangleHeight)
}
}