Search code examples
iosswiftxcodeuicollectionviewuikit

Difference between invalidateLayout() and reloadData()


I am wondering what some of the differences are between invalidateLayout() and reloadData() I have read the documentation here and here but am left with the following questions:

  1. I have data as an array such that cellForItemAt indexPath can reference the array directly with dataArray[indexPath.item] and each data object in the array can populate the cell. reloadData() will ensure that when a change is made to the dataArray this is reflected in the collectionView. With some minor testing it appears that invalidateLayout() will also observe this change. Is this always true?
  2. Both functions appear to have the same effect with regards to resizing the cells, is this always true?
  3. When invalidateLayout() is called, will cellForItemAt indexPath also be called for each cell as with reloadData()?
  4. If all the above are true, then would you ever even need to use reloadData() since Apple says to use it sparingly?

Any other comments on the differences between the two functions on a fundamental level would be helpful (when to use each one, etc)


Solution

  • After further testing...

    1. cellForItemAt indexPath will be called only for cells which were not on screen but are now on screen as a result of the invalidateLayout().
    2. This appears to be true
    3. See answer to question 1. This could cause an issue if you have moved cells around and the data in each cell is not in the same order as the data source.
    4. I am now using reloadData() a lot less

    In general, it looks like reloadData() also calls invalidateLayout() (or at least has a similar effect) and will trigger cellForItemAt indexPath for every cell. invalidateLayout(), however, will only call cellForItemAt indexdPath if the cell is now within the screen bounds and needs to be reloaded as a result of the layout change.