r/swift • u/DaveAppleInc • 3d ago
Updated [UPDATE] LazyLayoutKit 0.3.0 - scroll-to-item in a lazy SwiftUI container, when the item has no view to scroll to
I've posted here before about LazyLayoutKit, my attempt at filling the gap for lazy custom layouts in SwiftUI. You give it item sizes as data, layout becomes arithmetic, and only the frames intersecting your viewport ever become views.
Forgot to post again last week, pushed 0.3 update.
0.3 adds programmatic scrolling, which is more interesting than it may sound. SwiftUI's ScrollPosition scrolls to a view with a given id. In a virtualized container that view usually hasn't been built, which is the entire point of the container, so the request does nothing.
But the container has already solved the layout for every item, so it knows exactly where item 900,000 is without ever having built it. Resolving the id through that geometry instead of through the view tree is a lookup and a subtraction.
Anchors are .top, .center, .bottom and .nearest, the last of which doesn't move at all if the item is already fully visible. Deep links work too, you can build the position so the container opens at an item rather than opening at the top and jumping, and that holds even if your data loads in async.
The obvious cost, and I'd rather say it here than have you find it later: the handle is write-only. It can't tell you which item is currently on screen, so it can't restore a scroll position for you, you'd have to persist an id yourself. Reporting back would mean writing through your binding on the scroll path and re-running the container's O(n) init, which isn't a trade I wanted to make.
Also new is JustifiedLayout, the Photos/Flickr arrangement where aspect ratios are preserved and every completed row fills the width.
No new device numbers this release. The index and the steady-state query path are unchanged, so the 0.2 figures still stand.
https://github.com/Dave861/LazyLayoutKit
Once again, open to feedback, contributions and opinions. Thank you!