Swift 3 UICollectionChoose strange cell spacing

I wanted to create a simple UICollectionView; one cell with one label. The width of the cell and label should increase / decrease depending on the width of the text. The spacing between marks should be 1.

I tried to do it 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 the min spacing to 0 as a collection.

Result:

Picture

I thought I must have done something wrong, I went to Google and found CellSizeToFitLabel

This, however, changes the height of the cell, not the width (btw works). So I changed the static preferred MaxLayoutWidth = 50 to StringToWidth (SomeString: label.text!)

I expected this to work, however this was the result: image

I would love to know why this space is and how to fix it.

+3


source to share





All Articles