Video Tutorial: Custom Collection View Layouts Part 4: DIY – Stretchy Headers

Don’t know if you still read the comments but here’s a model that explains the math:

Untitled-1

The blue distance value will be positive (because the offset+center is larger than the blue cell’s center.y) and the pink distance negative (as the offset+center is smaller than the pink cell’s center.y). That’s where the abs() function comes in, which disregards positivity or negativity of the value and just gives back the absolute value. Subsequently, the sorted() function sorts the values and places the smallest one up front - which is then picked by “.first”. This is done for ALL cells, not just the ones visible on screen.

Hope that helps.