普通CollectionView单元中的动态CollectionView单元

问题描述 投票:0回答:1

我正在将故事板与CollectionView单元内的CollectionView一起使用。我需要一个内部来根据数组中给出的文本调整高度。在这一点上,我认为不存在任何示例。

ios swift uicollectionview uicollectionviewcell autoresize
1个回答
0
投票

这里是snippet,用于测量字符串的大小。 (您可能需要将默认值220更改为适合您的需求。)

extension String {
    func size(width:CGFloat = 220.0, font: UIFont = UIFont.systemFont(ofSize: 17.0, weight: .regular)) -> CGSize {
        let label:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: CGFloat.greatestFiniteMagnitude))
        label.numberOfLines = 0
        label.lineBreakMode = NSLineBreakMode.byWordWrapping
        label.font = font
        label.text = self

        label.sizeToFit()

        return CGSize(width: label.frame.width, height: label.frame.height)        
    }    
}

在您的collectionViewController中,确保您在视图控制器中继承UICollectionViewDelegateFlowLayout

class yourViewController : UICollectionViewController, UICollectionViewDelegateFlowLayout 

然后实现sizeForItemAt函数:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let yourString = yourStringArray[indexPath.row]
    return yourString.size(width: collectionView.frame.width) // you can also specify a font with fontSize and weight. Default is set to the system font with fontSize 17.
}

注意:您将需要根据单元格的外观向size添加填充。 “大小”仅根据标签的文本来衡量标签的大小。

© www.soinside.com 2019 - 2024. All rights reserved.