spacenation / swiftui-grid

:rocket: SwiftUI Grid layout with custom styles

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Lazy load items

sindresorhus opened this issue Β· comments

This is a very useful project. πŸ™Œ I use it to show a lot of images in a waterfall grid. However, the API I'm using uses pagination, so I need to load the next page from the API when the user scrolls to the bottom (actually before the bottom). Do you have any plans to add support for infinite grid? Or maybe hooks to enable this use-case?

@sindresorhus I think there is a way to do it right now. Let me double check and I'll get back to you.

@sindresorhus I just checked and this is as simple as doing this.

self.items += nextBatchOfItems

Just append new items to your array. Grid will see the change and recalculate the difference. It even preserves the scroll position. I'm going add this to examples and I'll post a reference here later.

@sindresorhus this however will only support loading items as they become available, not when user scrolled to the end on the grid. This is definitely something we should do but I'm not sure what is the best way to do it in SwiftUI now.

I did some more research on this and it seems like the common workaround for knowing when to lazy load is to use .onAppear on the elements. Would be nice if Grid could handle this somehow.

Example: https://github.com/crelies/List-Pagination-SwiftUI/blob/e41a0d0b2ffab260a14345e42e1cf1fa3822e1b2/SwiftUI-List-Pagination/View/ListPaginationExampleView.swift#L29-L31

@sindresorhus with the release 1.0.0 grid is now a lower level ui element (like HStack) and ScrollView has been removed from it. This means that behaviours like pull to refresh and lazy loading have to be added at a ScrollView level. I'm closing this because it is now out of scope for this project.

@ay42 This is a really good change. Makes it much more flexible. πŸ‘


I did some more research on this and it seems like the common workaround for knowing when to lazy load is to use .onAppear on the elements. Would be nice if Grid could handle this somehow.

I tried this out, but the elements in a Grid triggers onAppear for all elements right away, so it's not feasible...

@sindresorhus I'm experiencing the same behavior. Have you found a workaround for onAppear firing on all grid elements at once? I was thinking maybe calculating the current scroll position vs the position of the grid element, but not entirely sure if that would work.

No. I gave up on it. Went with paging instead. Hopefully, WWDC will bring enough SwiftUI improvements to make this feasible.

Hopefully, WWDC will bring enough SwiftUI improvements to make this feasible.

Amen to that :)

Thanks for the response.

For anyone that comes across this in the future, Apple added LazyHGrid and LazyVGrid which lazy loads items as they come into view. However, as far as I can tell, it's not as simple to implement a staggered grid with these views.