0

I have a collection view in which its cells resize dynamically depending on image orientation, label content etc.

This works perfectly and is basically achieved through the flow layout delegate method below.

extension TimelineViewController: UICollectionViewDelegateFlowLayout {

    func collectionView(
        _ collectionView: UICollectionView,
        layout collectionViewLayout: UICollectionViewLayout,
        sizeForItemAt indexPath: IndexPath
    ) -> CGSize {
        let resource = dataSource.items[indexPath.section].items[indexPath.row]
        resizingCell.model = resource
        let calculatedSize = resizingCell.contentView.systemLayoutSizeFitting(
            UILayoutFittingCompressedSize
        )
        return calculatedSize
    }
}

In case it makes a difference, resizingCell above is defined in my viewDidLoad method:

let identifier = String(describing: MyCell.self)
let cellNib = UINib(nibName: identifier, bundle: nil)
collectionView.register(cellNib, forCellWithReuseIdentifier: identifier)
resizingCell = cellNib.instantiate(withOwner: nil, options: nil).first as? MyCell

The problem with the above is that my delegate method is called for every single indexPath in my collection view even before it gets displayed on screen. The height calculation is relatively expensive and when I have upwards of +1000 items in my datasource it can take a few seconds for the collection view to even appear on screen.

Is this expected behaviour and if not, is there anything I can do about it? It sort of defeats the purpose of reusable cells if I have to calculate the size of each upfront.

Thanks for looking into this.

Rog
  • 18,602
  • 6
  • 76
  • 97
  • Can't you use just estimated item size, it should compute size on its own? Here is a tutorial what I found https://medium.com/@wasinwiwongsak/uicollectionview-with-autosizing-cell-using-autolayout-in-ios-9-10-84ab5cdf35a2 – Luzo Oct 23 '17 at 06:32
  • `UICollectionView` is a subclass of `UIScrollView`. To calculate the `contentSize` of the collection view this method is called for each indexPath. What you are pointing to is the normal behaviour. May your dataSource contain a lot of items then use pagination and add chunks of items in the dataSource. – Adeel Miraj Oct 23 '17 at 06:46
  • That doesn’t make any sense. The content size can be adjusted as the collection view is scrolled, in fact this is exactly what you get with the table view equivalent height for row at indexPath – Rog Oct 23 '17 at 07:50

0 Answers0