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.