Created
October 27, 2021 16:48
-
-
Save ryanlintott/c0ce02a7d54b782e02a8329649a597ad to your computer and use it in GitHub Desktop.
LazyDataVStack
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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