Skip to content

Instantly share code, notes, and snippets.

@StefKors
Created March 16, 2023 12:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save StefKors/0f31b47bc90ebca7fdbba58acc0ee25b to your computer and use it in GitHub Desktop.
Save StefKors/0f31b47bc90ebca7fdbba58acc0ee25b to your computer and use it in GitHub Desktop.
Example of SwiftUI Data loading with LazyVStack and ScrollViews. First you create an array with some identifier of your long list. Then in the child view you use `.task { }` to load the data based of the ID. The LazyVStack will take care of loading the next view.
//
// LazyContentWindow.swift
// Commitment
//
// Created by Stef Kors on 16/03/2023.
//
import SwiftUI
struct LazyLoadedView: View {
let id: String
@State private var hasLoaded: Bool = false
var body: some View {
GroupBox {
Text(id)
Text("hasLoaded:\(hasLoaded.description)")
}
.overlay(content: {
if hasLoaded == false {
ProgressView("is loading")
.progressViewStyle(.linear)
.background(.background.opacity(0.8))
}
})
.frame(width: 400, height: 50, alignment: .leading)
.task {
print("loading \(id)")
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1), execute: {
withAnimation(.stiffBounce) {
hasLoaded = true
}
})
}
}
}
struct LazyContentWindow: View {
@State private var profiles: [String] = []
var body: some View {
ScrollView(.vertical) {
LazyVStack {
ForEach(profiles, id: \.self) { profile in
LazyLoadedView(id: profile)
Divider()
}
}
}
.frame(maxWidth: 400, maxHeight: 600)
.task {
profiles = Array(1..<1000).map({ Int in
return "#\(Int)|\(UUID().uuidString)"
})
}
}
}
struct LazyContentWindow_Previews: PreviewProvider {
static var previews: some View {
LazyContentWindow()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment