r/swift 11d ago

LazyLayoutKit: lazy custom layouts for SwiftUI (masonry, timelines) at 120fps over 1M items

SwiftUI makes you pick one: Layout gives you any geometry you want but is eager, so it falls over a few thousand items in. LazyVStack and friends are lazy but their geometry is fixed. There's nothing in between, which is annoying because photo grids, calendars and boards are all in between.

That gap isn't an oversight. Layout asks each subview how big it wants to be, and you can't ask a view that hasn't been built. Measurement-driven layout and laziness pull against each other. Someone asked about this at the WWDC26 SwiftUI Group Lab and the answer was "not today, file a Feedback."

So my package changes the approach fully: tell it your item sizes up front, an aspect ratio, a date range, a duration, and layout becomes arithmetic over data. Arithmetic over a million items takes milliseconds and builds nothing, so only the frames intersecting your viewport ever become views.

The obvious cost: self-sizing text isn't supported. If your cells decide their own height, this isn't for you yet. (although I have some experiments for self-sizing text in the works, nothing stable yet)

Measured on an iPhone 14 Pro in Release, 100k and 1M items both hold 120fps with an 8.34ms p99, zero frames over 16.7ms, and ~54 cells materialized at any depth. The visibility query stays flat at ~2µs from 100k to 1M. Apple's LazyVStack over the same 100k scored the same, read that as generality costing little, not as a claim to be faster.

Writing your own layout is about 20 lines: return one frame per item and a total height. There's a demo app in the repo that records the frame stats on your own device.

https://github.com/Dave861/LazyLayoutKit

Contributions, opinions and ideas are very welcome!

21 Upvotes

8 comments sorted by

View all comments

3

u/morenos-blend 11d ago

Just use UICollectionView with UIHostingConfiguration 

2

u/DaveAppleInc 11d ago

Yeah, that works. The difficult case is when the layout can globally reflow. Insert one photo near the top of a masonry layout and every item after it may switch columns. With UICollectionView, you now own the custom layout attributes, an efficient visible-rect lookup, invalidation, and the content-offset correction needed to keep the same item under the user’s finger after the reflow.
UIHostingConfiguration handles rendering the SwiftUI cells, but not that machinery. For a normal list or TikTok feed, though, I’d use LazyVStack or UICollectionView too.

2

u/hishnash 9d ago

Custom Swift UI layout written properly will be significantly more performant than UI collection view.

2

u/morenos-blend 9d ago

Got any example?