Dynamic cell width of UICollectionView depending on label width

前端 未结 7 1363
别跟我提以往
别跟我提以往 2020-11-28 02:44

I have a UICollectionView, that loads cells from reusable cell, which contains label. An array provides content for that label. I can resize label width depending on content

7条回答
  •  清酒与你
    2020-11-28 03:04

    I have found a small trick for swift 4.2

    For dynamic width & fixed height:

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
            let label = UILabel(frame: CGRect.zero)
            label.text = textArray[indexPath.item]
            label.sizeToFit()
            return CGSize(width: label.frame.width, height: 32)
        }
    

    For dynamic height & fixed width:

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
                let label = UILabel(frame: CGRect.zero)
                label.text = textArray[indexPath.item]
                label.sizeToFit()
                return CGSize(width: 120, height: label.frame.height)
            }
    

提交回复
热议问题