0

In my app I have a collection view with cells autosizing horizontally. Here's some code:

// called in viewDidLoad()

private func setupCollectionView() {
    let cellNib = UINib(nibName: SomeCell.nibName, bundle: nil)
    collectionView.register(cellNib, forCellWithReuseIdentifier: SomeCell.reuseIdentifier)

    guard let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout else { return }

    flowLayout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
    flowLayout.itemSize = UICollectionViewFlowLayout.automaticSize
}

The cell has 1 view, which has constraint for heigth. This view subviews a label, which is limited with 2 rows and is not limited by width. The idea here is to allow label to calculate its own width fitting text in 2 rows.

In order to make this work I've added the following code to the cell class:

override func awakeFromNib() {
    super.awakeFromNib()

    contentView.translatesAutoresizingMaskIntoConstraints = false

    contentView.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
    contentView.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
    contentView.topAnchor.constraint(equalTo: topAnchor).isActive = true
    contentView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
}

Now, it works perfectly. Cells are autosizng, scrollView is scrolling horizontally etc. Until I call reloadData() at least once. Then cells have size 50x50 and never autosize any more until I leave the screen and come back again.

Do you have any ideas on why is it happening?

Robert Dresler
  • 10,580
  • 2
  • 22
  • 40
Yevgeniy Leychenko
  • 1,287
  • 11
  • 25

0 Answers0