根据标签文本自定义 UICollectionViewCell 自身大小

Posted

技术标签:

【中文标题】根据标签文本自定义 UICollectionViewCell 自身大小【英文标题】:Custom UICollectionViewCell self size according to the label text 【发布时间】:2020-03-10 14:52:32 【问题描述】:

我创建了一个 UICollectionViewCell xib,并希望单元格根据标签文本的长度自动调整,如下图所示。

图片显示了我在原型单元上制作的内容。但无论我怎么尝试,当我使用 xib 时,单元格的大小都保持不变。

【问题讨论】:

【参考方案1】:

实现这个委托 UICollectionViewDelegateFlowLayout

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize 

        let market = self.markets[indexPath.row]
        let label = UILabel(frame: CGRect.zero)
        label.text =  market
        label.sizeToFit()
        return CGSize(width: label.frame.width, height: 25)
    

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize 
        let text = NSAttributedString(string: markets[indexPath.row])
        return CGSize(width: text.size().width, height: 25)
    

【讨论】:

【参考方案2】:

你也可以在 sizeForItemAt 中实现这个 只需插入“yourString”和“yourFont”:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize 

    let width = yourString.size(withAttributes: [NSAttributedString.Key.font: yourFont]).width
    return CGSize(width: width, height: 20) 

由于单元格的角半径,您可能需要在宽度上添加一些空间

【讨论】:

以上是关于根据标签文本自定义 UICollectionViewCell 自身大小的主要内容,如果未能解决你的问题,请参考以下文章