0

I have a UICollectionView that acts as a list of tags.

It uses a horizontal compositional layout.

Here is a screenshot: list of tags

My problem is that if I have a tag longer than the collection's width, it crashes with the following error:

Error: NSCollectionLayoutItem created with invalid combination of spacing and size specified. This group cannot fit even a single item.

I understand the error, it makes sense. But how do I force the UILabel (only component of the UICollectionViewCell) to break lines?

I have set numberOfLines to 0. The ViewCell is loaded from a xib with autolayout which is very basic (the UILabel is sticking to superview).

And finally the code for the Compositional is the following:

let layoutSize = NSCollectionLayoutSize(widthDimension: .estimated(50), heightDimension: .estimated(20))
let item = NSCollectionLayoutItem(layoutSize: layoutSize)

let group = .horizontal(layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: layoutSize.heightDimension), subitems: [item])
group.interItemSpacing = .fixed(10)

let section = NSCollectionLayoutSection(group: group)
section.contentInsets = .init(top: 4, leading: 16, bottom: 4, trailing: 16)
let layout = UICollectionViewCompositionalLayout(section: section)

let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)

I can't figure out what blocks the UILabel from breaking into multiple lines?

1 Answer 1

0

Looking to your collectionView setup.

I think below is the problem

let layoutSize = NSCollectionLayoutSize(widthDimension: .estimated(50), heightDimension: .estimated(20)) 

estimated means: Dimension is estimated with a point value. Actual size will be determined when the content is rendered. So whenever your text is long its width over the screen sized cause error.

In order to have line break, the collection view cell needs to know its width ( which can not be flexible). There are two ways for you to fix this error.

Example I have below data

let listValue = ["cafeaawewqeqwewqweqweqweeqeeqweqweqweqwe", "pub", "motorcycle", "laundrette", "bar", "to walk", "embassy"]

First one using absolute width. Means that Dimension with an absolute point value

let layoutSize = NSCollectionLayoutSize(widthDimension: .absolute(50), heightDimension: .estimated(20)) 

First

Second one using fractionalWidth. Means that Dimension is computed as a fraction of the width of the containing group.

let layoutSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(0.5), heightDimension: .estimated(20))

Second

Read more

Not the answer you're looking for? Browse other questions tagged or ask your own question.