4

I have a LazyVGrid that displays search results, as I type characters in the search field, I perform CoreData fetch requests and update a @Published property.

Problem:
LazyVGrid updates results as expected EXCEPT if it is currently scrolling: in this case it will wait for the scroll to decelerate and end before refreshing.

For comparaison, in UIKit I could use a UICollectionView and call .reloadData() on it, it would refresh the grid immediately regardless of it scrolling or not.

For testing purposes, I tried without success the following:

  • Add .animation(nil) view modifier
  • Add .id(UUID()) view modifier
  • Update a @State var dummy = "" when I wanna refresh the view, and use it in the view's body, eg: Text(dummy)

Bellow is some code to help visualize how this thing works

struct SearchResultGroup: Hashable {
    let title: String?
    let list: [Foo] // Foo is a NSManagedObject class representation
}
class SearchResultsHolder: ObservableObject {
    @Published var results: [SearchResultGroup] = []
}
struct SearchResultsSV: View {
    @ObservedObject var searchResultsHolder: SearchResultsHolder // searchResults.results property gets updated externally
    
    var body: some View {
        
        LazyVGrid(columns: [GridItem(.adaptive(minimum: 30))]) {
            ForEach(searchResultsHolder.results, id: \.self) { section in
                Section(header: Text( section.title ?? ""))
                        , content: {
                            ForEach(section.list, id: \.id) { foo in
                                    Text(foo.bar)
                            }
                        })
            }
        }
    }

Any idea how I can make a LazyVGrid refresh it's content event while it's scrolling animation is running? Otherwise it feels unresponsive for users.

Kuringan
  • 147
  • 6
  • In short you need to observe the `NSManagedObject` and the store. If you are retrieving your `[Foo]` without a SwiftUI`@FetchRequest` or an `NSFetchedRequestController` you are not listening for changes in the store. Watch [What is new in SwiftUI](https://developer.apple.com/wwdc21/10018) for an iOS 15+ solution for [iOS 13 and iOS14 see this question](https://stackoverflow.com/questions/67526427/swift-fetchrequest-custom-sorting-function/67527134#67527134) – lorem ipsum Jul 18 '21 at 21:43

0 Answers0