Last active
June 27, 2024 10:51
-
-
Save benigumocom/bf3e3a4fc074144ba35736ece4943fb4 to your computer and use it in GitHub Desktop.
【SwiftUI + SwiftData】ScrollView + LazyVStack vs Large amounts of data 👉 https://android.benigumo.com/20240627/scrollview-lazyvstack-vs-large-amounts-of-data/
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
import SwiftUI | |
import SwiftData | |
@Model | |
final class Item { | |
var i: Int | |
var s: String | |
init(i: Int, s: String) { | |
self.i = i | |
self.s = s | |
} | |
} | |
struct TestLazyStack: View { | |
@Environment(\.modelContext) private var modelContext | |
@Query(sort: \Item.s) private var items: [Item] | |
private let size = 1_000 | |
var body: some View { | |
ScrollView { | |
LazyVStack { | |
ForEach(items) { item in | |
Text("\(item.i) | \(item.s)") | |
.monospaced() | |
} | |
} | |
} | |
.onAppear { | |
clear() | |
generate() | |
} | |
} | |
private func clear() { | |
try? modelContext.delete(model: Item.self) | |
} | |
private func generate() { | |
(0 ..< size).forEach { i in | |
modelContext.insert( | |
Item(i: i, s: String(format: "%04d", i)) | |
) | |
} | |
} | |
} | |
#Preview { | |
let container = try! ModelContainer(for: Schema([Item.self])) | |
return TestLazyStack() | |
.modelContainer(container) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment