I wanted to create a simple UICollectionView ; one cell which has one label. The cell and label width should increase / decrease based on the width of the text. The spacing between the labels should be 1.
I tried to do that with the following code :
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let ab = items[indexPath.item] --> The string of the cell
var width1 = StringToWidth(SomeString: ab) // Calculate the width of the text
width1 = width1 * 1.1 // Looks better
return CGSize(width: width1, height: 50)
}
//Lines
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat{
return 1
}
// Spaces
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat{
return 1
}
In the storyboard I set min spacing to 0 of the collection view.
The result:
I thought I must have done something wrong I went to google and found CellSizeToFitLabel
This however changes the height of the cell instead of the width(it works btw). So I changed the static preferredMaxLayoutWidth = 50 to StringToWidth(SomeString: label.text!)
I expected this to work , however this was the result :
I would love to know why it spaces like that and how to fix it