Search code examples
iosswiftswiftuilazy-loadinglazyvstack

How to set a custom prefetching time for LazyVStack in SwiftUI?


TL;DR: Is there some parameter or way to set the offset at which LazyVStack initialises views?

LazyVStack initialises the views lazily, so when I scroll, the next (few?) views are initialised. I am loading an image once a view is drawn, using SDWebImage Package in swift. This takes a view milliseconds, and since I am using a LazyVStack, if one scrolls fast (even within reasonable limits), the placeholder is visible for a short moment, because the view has just been created a (too) short moment ago. If I scroll very slowly, the image loads just before the view appears, so no placeholder is visible.

If I could make the LazyVStack initialise the views just a few milliseconds earlier my problem would be gone...

Once would think this is a pretty common problem, timing this initialisation just right so as not to load too early or too late.. but nothing at all in the docs about this


Solution

  • Quick answer to the question: no


    That being said, in this case there is still a solution: Since I was using SDWebImageSwiftUI before, simply calling the following already before the view starts to initialise solved my problem:

    SDWebImagePrefetcher.shared.prefetchURLs(urls) { finishedCount, skippedCount in
         print("preloading complete")
    }
    

    then in my LazyVStack I use:

    LazyVStack {
         ForEach(items, id: \.self) { item in
                 ItemView(item: item)
                       .onAppear {
                            // calling function to prefetch next x-items by their url
                      }
                }
         }
    }