-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathLifecycleMonitor.swift
92 lines (85 loc) · 2.95 KB
/
LifecycleMonitor.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import SwiftUI
/// A view that records and displays its lifecycle events.
struct LifecycleMonitor: View {
var label: String
@State private var stateTimestamp: Date = .now
@State private var onAppearTimestamp: Date? = nil
@State private var onDisappearTimestamp: Date? = nil
@State private var color: Color = .random()
var body: some View {
VStack(spacing: 16) {
Text(label)
.font(.title3)
Grid(horizontalSpacing: 16) {
GridRow(alignment: .firstTextBaseline) {
Text("@State")
.gridColumnAlignment(.leading)
Text("\(stateTimestamp, style: .timer) ago")
.monospacedDigit()
.gridColumnAlignment(.leading)
}
.help("When the state (incl. @State and @StateObject) for this view was created")
GridRow(alignment: .firstTextBaseline) {
Text("onAppear")
Text(timestampLabel(for: onAppearTimestamp))
.monospacedDigit()
}
.help("When onAppear was last called for this view")
GridRow(alignment: .firstTextBaseline) {
Text("onDisappear")
Text(timestampLabel(for: onDisappearTimestamp))
.monospacedDigit()
}
.help("When onDisappear was last called for this view")
}
.font(.callout)
}
.padding()
.frame(maxWidth: .infinity)
.background {
RoundedRectangle(cornerRadius: 16)
.fill(color)
}
.onAppear {
let timestamp = Date.now
print("\(timestamp) \(label): onAppear")
let animation: Animation? = onAppearTimestamp == nil ? nil : .easeOut(duration: 1)
withAnimation(animation) {
onAppearTimestamp = timestamp
}
}
.onDisappear {
let timestamp = Date.now
print("\(timestamp) \(label): onDisappear")
let animation: Animation? = onDisappearTimestamp == nil ? nil : .easeOut(duration: 1)
withAnimation(animation) {
onDisappearTimestamp = timestamp
}
}
}
private func timestampLabel(for timestamp: Date?) -> LocalizedStringKey {
if let t = timestamp {
return "\(t, style: .timer) ago"
} else {
return "never"
}
}
}
struct LifecycleMonitor_Previews: PreviewProvider {
static var previews: some View {
List {
ForEach(1..<100) { i in
LifecycleMonitor(label: "\(i)")
}
}
}
}
extension Color {
static func random() -> Self {
Color(
red: .random(in: 0.5...0.9),
green: .random(in: 0.5...0.9),
blue: .random(in: 0.5...0.9)
)
}
}