Use the .introspect modifier to access underlying views
mainThe .introspect modifier allows you to access the underlying UIKit or AppKit view for a SwiftUI view.
Important Requirements:
- Explicit Opt-in: You must specify the platform and version (e.g.,
.iOS(.v17, .v18)) because underlying types can change between major OS versions. - Scope: By default,
.introspectacts on its receiver. To introspect an ancestor view instead, setscope: .ancestor.
Best Practices:
- Use sparingly: Prefer native SwiftUI modifiers when available.
- Program defensively: The closure may be called multiple times during the view lifecycle; ensure your code handles re-execution without side effects.
- Avoid direct state changes: Do not change SwiftUI state inside the closure. If necessary, wrap updates in
DispatchQueue.main.async. - Avoid retain cycles: Use
[weak self]when capturing references.
ScrollView {
Text("Item 1")
}
.introspect(.scrollView, on: .iOS(.v17, .v18, .v26, .v27)) { scrollView in
// do something with UIScrollView
}