-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathCaseStudyScrollViewDynamic.swift
63 lines (60 loc) · 2.19 KB
/
CaseStudyScrollViewDynamic.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import SwiftUI
struct CaseStudyScrollViewDynamic: View {
private static let initialItemCount = 40
@State private var items: [Item] = (1...Self.initialItemCount).map { i in
Item(id: "Item \(i)")
}
@State private var nextID: Int = Self.initialItemCount + 1
var body: some View {
ScrollView {
VStack {
ForEach(items) { item in
HStack {
LifecycleMonitor(label: item.id)
Button(role: .destructive) {
if let idx = items.firstIndex(where: { $0.id == item.id }) {
items.remove(at: idx)
}
} label: {
Label("Delete", systemImage: "minus.circle")
.labelStyle(.iconOnly)
}
}
.padding()
}
}
}
.safeAreaInset(edge: .bottom) {
Text("Unlike `List`, a `ScrollView` has no effect on its content views’ lifecycle, even if those content views are created dynamically with `ForEach`. All children appear at once and never disappear, even if they’re not on screen initially.")
.font(.callout)
.padding()
.frame(maxWidth: .infinity, alignment: .leading)
.background(.regularMaterial)
}
.toolbar {
ToolbarItem {
Button("Prepend") {
let newItem = Item(id: "Item \(nextID)")
nextID += 1
items.insert(newItem, at: 0)
}
}
ToolbarItem {
Button("Append") {
let newItem = Item(id: "Item \(nextID)")
nextID += 1
items.append(newItem)
}
}
}
.animation(.default, value: items)
.navigationTitle("Dynamic ScrollView")
}
}
struct CaseStudyScrollViewVStackForEach_Previews: PreviewProvider {
static var previews: some View {
NavigationStack {
CaseStudyScrollViewDynamic()
}
}
}