Last active
February 7, 2026 16:01
-
-
Save satishVekariya/fea6cb5930639144128aefec9605a649 to your computer and use it in GitHub Desktop.
Lazy loads swiftui view in the List
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
| /// ForEach that renders items in batches for smoother scrolling | |
| public struct BatchedForEach<Data, ID, Content>: View | |
| where Data: RandomAccessCollection, | |
| Data.Index == Int, | |
| ID: Hashable, | |
| Content: View { | |
| @State private var renderedCount: Int | |
| private let data: Data | |
| private let id: KeyPath<Data.Element, ID> | |
| private let batchSize: Int | |
| private let content: (Data.Element) -> Content | |
| public init( | |
| _ data: Data, | |
| id: KeyPath<Data.Element, ID>, | |
| batchSize: Int = 20, | |
| @ViewBuilder content: @escaping (Data.Element) -> Content | |
| ) { | |
| self.data = data | |
| self.id = id | |
| self.batchSize = batchSize | |
| self.content = content | |
| self._renderedCount = State(initialValue: min(batchSize, data.count)) | |
| } | |
| public var body: some View { | |
| ForEach(0..<renderedCount, id: \.self) { index in | |
| content(data[index]) | |
| .onAppear { | |
| loadMoreIfNeeded(currentIndex: index) | |
| } | |
| } | |
| } | |
| private func loadMoreIfNeeded(currentIndex: Int) { | |
| // Load next batch when approaching the end | |
| if currentIndex >= renderedCount - 5 && renderedCount < data.count { | |
| renderedCount = min(renderedCount + batchSize, data.count) | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment