CollectionView 自动调整大小标签不起作用

CollectionView AutoResize Label Not Working

我有一个带标签的垂直集合视图,在我的流程布局中,我正在使用 UICollectionViewFlowLayoutAutomaticSize 来调整单元格大小,但是当我给出很长的时间时它会给我错误字符串到标签,行数 label 设置为 0

错误

Please check the values returned by the delegate. The relevant

UICollectionViewFlowLayout instance is UICollectionViewFlowLayout ,and it is attached to UICollectionView; frame = (0 88; 375 690); clipsToBounds = YES; autoresize = RM+BM; gestureRecognizers = NSArray layer = CALayer; contentOffset: {0, 0}; contentSize: {375, 2}; adjustedContentInset: {0, 0, 0, 0}> collection view layout: UICollectionViewFlowLayout

Make a symbolic breakpoint at UICollectionViewFlowLayoutBreakForInvalidSizes to catch this in the debugger.

The behavior of the UICollectionViewFlowLayout is not defined because the item width must be less than the width of the UICollectionView minus the section insets left and right values, minus the content insets left and right values

约束条件

代码

let array = ["Hello", Array(repeating: "Hello", count: 100).joined(), "blah"]
// on viewDidLoad method
 if let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
        flowLayout.estimatedItemSize = CGSize(width: 1, height: 1)
        flowLayout.itemSize = UICollectionViewFlowLayoutAutomaticSize
    }

问题是由于某些原因 UICollectionViewFlowLayout 没有设置单元格的最大宽度,并且由于您像您一样设置了约束,所以会发生 width 一个或多个单元格单元格大于 collectionView 的宽度。

解决方法如下,在 UICollectionViewCell 子类内的标签中添加 width 约束,并将其设置为 less than equal 而不是 equal

接下来为该约束创建一个出口,以便以后可以设置它。

然后在 CollectionViewDataSource cellForItemAtIndexPath 中,您可以将宽度常量设置为小于 CollectionView 宽度减去您添加的填充(在我的例子中,标签的左右填充为 20 + 20对)。

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "reuse", for: indexPath) as! CollectionViewCell

    cell.widthConstraint.constant = collectionView.bounds.size.width - 40
    //line above sets maximum width of label to be maximum the width of the collection view
    cell.label.text = array[indexPath.item]
    return cell
}

结果是如下所示的集合视图: