提问人:dax tech 提问时间:9/30/2023 最后编辑:dax tech 更新时间:9/30/2023 访问量:41
所有 CollectionViewCell 高度等于 swift 中最大的单元格标签动态内容
All CollectionViewCell height equal to largest cell label dynamic content in swift
问:
所有 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)
}
}
答:
0赞
Mykyta iOS
9/30/2023
#1
let height = cellHeights.max()
return CGSize(width:collectionView.frame.width, height: height)
重写委托方法以获取最大单元格高度,而不是按索引选择一个单元格。
评论