I created a UICollectionView with a custom cell. In the viewDidLoad() method I was registering my cellclass.
collectionView?.register(CustomCell.self, forCellWithReuseIdentifier: cellId)
collectionView?.reloadData()
While debugging my code to check the behavior I saw that in the line where I was registering my collectionView and called collectionView.reloadData() with the custom Cellclass none of the datasource and delegate methods got executed like cellForItem at etc.. ? Why is that so ?
viewDidLoad() is called when your view has finished loading but before the view is laid out i.e. before its frame is properly set.
Judging from my observations a collection view calls its data source methods (like cellForItem(at:)) lazily during the layout process. After all, it doesn't need to call the data source methods at all if its size is .zero or if its position is currently off-screen!
There is no reason why your collection view's data source methods should be called in viewDidLoad().
As far as I know calling reloadData() only discards all visible cells and decoration views so that they must be reloaded during the next layout pass. When the collection view is currently visible a new layout pass is triggered immediately but in viewDidLoad() the collection view isn't even on screen yet. (viewDidAppear() has not been called yet.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With