iOS-动态调整UICollectionViewCell的宽度

问题描述

我只是想动态调整单元格的大小。我遵循了几个SO问题,似乎无法产生相同的结果。 Example one Example two

我现在的代码是:

extension ItemViewController: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView,layout collectionViewLayout: UICollectionViewLayout,sizeforItemAt indexPath: IndexPath) -> CGSize {
        let text = allTags[indexPath.item]
        tagName.text = text //label from my custom cell (xCode not recognizing)
        return CGRect(width: tagName.intrinsicContentSize.width + 60,height: 40)
}
}

在第二行中,Xcode未标识tagName。这是我的自定义单元格类的一部分。我以某种方式链接的第一个SO问题能够在sizeforItemAt中识别其单元格属性。我该如何动态调整单元格大小?我的估计尺寸确实为非零:

if let collectionViewLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
            collectionViewLayout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
}

我想要的结果类似于照片。让我知道您是否需要更多信息。谢谢。

enter image description here

enter image description here

解决方法

x = 0.213099234     // n = 9
y = 0.2130992347    // n = 10
...
,

尝试这种方式。 在Swift5中对我来说效果很好。

首先实施 Collectionview FlowLayout委托

extension ItemViewController: UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView,layout collectionViewLayout: UICollectionViewLayout,sizeForItemAt indexPath: IndexPath) -> CGSize {
        
        let text = "Your Lable Text"
        let font: UIFont = UIFont(name: "Font Name",size: 20) ??  UIFont.systemFont(ofSize: 17.0) // set here font name and font size
        let width = text.SizeOf(font).width
        return CGSize(width: width + 20.0,height: 40.0) // ADD width + space between text (for ex : 20.0)
        }    
}

添加一个字符串扩展名

extension String {
    
    func SizeOf(_ font: UIFont) -> CGSize {
        return self.size(withAttributes: [NSAttributedString.Key.font: font])
    }
    
}