1

I have a collectionView where the cells have a dynamic width. The problem is that the cells are aligned in the center, and I want it to be aligned to the left, look at the picture, I drew a red line where I want the alignment:

Screen

Here my collection view configuration:

var collectionView: UICollectionView = {
    let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    layout.itemSize = CGSize(width: 100, height: 40)
    layout.scrollDirection = .horizontal
    layout.minimumLineSpacing = 0

    let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
    collectionView.setCollectionViewLayout(layout, animated: true)
    collectionView.register(SportsCell.self, forCellWithReuseIdentifier: "MyCell")
    collectionView.translatesAutoresizingMaskIntoConstraints = false
    collectionView.backgroundColor = .white
    collectionView.showsHorizontalScrollIndicator = false

    return collectionView
}()

Then the method to make the size dynamic:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let text = items[indexPath.row].message
    let padding: CGFloat = 5

    return CGSize(width: textWidth(text: text, font: .systemFont(ofSize: 22)) + padding, height: 40)
}

func textWidth(text: String, font: UIFont?) -> CGFloat {
    let attributes = font != nil ? [NSAttributedString.Key.font: font!] : [:]
    return text.size(withAttributes: attributes).width
}
Mickael Belhassen
  • 2,970
  • 1
  • 25
  • 46

0 Answers0