@@ -31,6 +31,7 @@ struct InspectLayout: ViewModifier {
31
31
. offset ( x: inspectorFrame. minX, y: inspectorFrame. minY)
32
32
. coordinateSpace ( name: Self . coordSpaceName)
33
33
}
34
+ . environment ( \. didCallInspectLayout, true )
34
35
. environmentObject ( logStore)
35
36
}
36
37
@@ -90,21 +91,43 @@ struct InspectLayout: ViewModifier {
90
91
}
91
92
}
92
93
94
+ enum DidCallInspectLayout : EnvironmentKey {
95
+ static var defaultValue : Bool = false
96
+ }
97
+
98
+ extension EnvironmentValues {
99
+ var didCallInspectLayout : Bool {
100
+ get { self [ DidCallInspectLayout . self] }
101
+ set { self [ DidCallInspectLayout . self] = newValue }
102
+ }
103
+ }
104
+
93
105
@available ( macOS 13 . 0 , iOS 16 . 0 , tvOS 16 . 0 , watchOS 9 . 0 , * )
94
106
struct DebugLayoutModifier : ViewModifier {
95
107
var label : String
96
108
var file : StaticString
97
109
var line : UInt
110
+ @Environment ( \. didCallInspectLayout) private var didCallInspectLayout
111
+ /// The log store for the current inspectLayout() subtree.
112
+ ///
113
+ /// - Important: You must verify that `didCallInspectLayout == true` before accessing
114
+ /// this property. Failure to do so will result in a crash as the object won't be
115
+ /// in the environment.
98
116
@EnvironmentObject private var logStore : LogStore
99
117
100
118
func body( content: Content ) -> some View {
101
- DebugLayout ( label: label, logStore: logStore) {
119
+ if didCallInspectLayout {
120
+ DebugLayout ( label: label, logStore: logStore) {
121
+ content
122
+ }
123
+ . onAppear {
124
+ logStore. registerViewLabelAndWarnIfNotUnique ( label, file: file, line: line)
125
+ }
126
+ . modifier ( DebugLayoutSelectionHighlight ( viewID: label) )
127
+ } else {
128
+ let _ = runtimeWarning ( " %@:%llu: Calling .layoutStep() without a matching .inspectLayout() is illegal. Add .inspectLayout() as an ancestor of the view tree you want to inspect. " , [ String ( describing: file) , UInt64 ( line) ] , file: file, line: line)
102
129
content
103
130
}
104
- . onAppear {
105
- logStore. registerViewLabelAndWarnIfNotUnique ( label, file: file, line: line)
106
- }
107
- . modifier ( DebugLayoutSelectionHighlight ( viewID: label) )
108
131
}
109
132
}
110
133
0 commit comments