Skip to content

Instantly share code, notes, and snippets.

@ryanlintott
Created October 27, 2021 16:48
Show Gist options
  • Save ryanlintott/c0ce02a7d54b782e02a8329649a597ad to your computer and use it in GitHub Desktop.
Save ryanlintott/c0ce02a7d54b782e02a8329649a597ad to your computer and use it in GitHub Desktop.
LazyDataVStack
//
// LazyDataVStack.swift
//
//
// Created by Ryan Lintott on 2021-03-31.
//
import SwiftUI
import CoreData
// Designed to fix scrolling glitches for sets of data with varying heights
struct LazyDataVStack<T: NSManagedObject, Content: View>: View {
var fetchRequest: FetchRequest<T>
let numVStackItems: Int
let alignment: HorizontalAlignment
var entities: FetchedResults<T> {
fetchRequest.wrappedValue
}
var firstEntities: Slice<FetchedResults<T>> {
entities.prefix(numVStackItems)
}
var remainingEntities: Slice<FetchedResults<T>> {
entities.dropFirst(numVStackItems)
}
let content: (T) -> Content
init(_ type: T.Type, numVStackItems: Int = 8, alignment: HorizontalAlignment = .center, predicate: NSPredicate? = nil, sortDescriptors: [NSSortDescriptor] = [], @ViewBuilder content: @escaping (T) -> Content) {
self.numVStackItems = numVStackItems
self.alignment = alignment
self.fetchRequest = FetchRequest<T>(entity: T.entity(), sortDescriptors: sortDescriptors, predicate: predicate)
self.content = content
}
var body: some View {
VStack(alignment: alignment, spacing: 0) {
if !firstEntities.isEmpty {
ForEach(firstEntities, id: \.self) { data in
content(data)
}
}
if !remainingEntities.isEmpty {
LazyVStack(alignment: alignment, spacing: 0) {
ForEach(remainingEntities, id: \.self) { data in
content(data)
}
}
}
}
}
}
struct LazyDataVStack_Previews: PreviewProvider {
static var previews: some View {
LazyDataVStack(CoreDataEntry.self) { data in
Text(data.name)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment