SwiftUI subviews traverse issue

Our project include UIKIt and SwiftUI, and in some case, we need to traverse all subviews, for UIKit implement views, below code:

    func findView(byIdentifier identifier: String) -> UIView? {
        if self.accessibilityIdentifier == identifier {
            return self
        }
        for subview in subviews {
            if let found = subview.findView(byIdentifier: identifier) {
                return found
            }
        }
        return nil
    }

works well, but for SwiftUI implement views, like below code:

struct ContentView: View {
    var body: some View {
        VStack {
            Image(systemName: "globe")
                .imageScale(.large)
                .foregroundStyle(.tint)
                .accessibilityIdentifier("Image")

            Text("Hello, world!")
                .accessibilityIdentifier("Text")
        }
        .padding()
    }
}

it can not find subviews in the ContentView, and only a view with type:

_UIHostingView<ModifiedContent<AnyView, RootModifier>>

can be found, the Image and Text is not found; And because we have set a accessibilityIdentifier property, so we also try use:

@MainActor
var accessibilityElements: [Any]? { get set }

to find sub node, but this accessibilityElements is not stable, we can find the Image and Text node in iOS26.1 system:

[AX] level=3 AccessibilityNode @ 0x000000010280fb10 id=Image
[AX] level=3 AccessibilityNode @ 0x000000010161fbf0 id=Text

but can not find it in iOS26.0 and below system. Any suggestion in how to find SwiftUI subviews? thank you

SwiftUI view hierarchy is internal to the framework. When using SwiftUI, you won't need to traverse the view hierarchy – If you do, I'd say that you probably aren't on the right track...

Having said that, I'm quite curious why you need to traverse the view hierarchy in SwiftUI. Would you mind to share?

Best,
——
Ziqiao Chen
 Worldwide Developer Relations.

No, I don't think there is a way to find a SwiftUI view via its accessibilityIdentifier. If your intent is to retrieve the frame of a Text and do something based on that in a parent view, GeometryReader + PreferenceKey / anchorPreference will be the way to go, even though it needs "some additional code."

In iOS 16, onGeometryChange(for:of:action:) allows you to perform an action when a geometry value of a view changes. If you target iOS 16 and later, that may be even easier.

Best,
——
Ziqiao Chen
 Worldwide Developer Relations.

SwiftUI subviews traverse issue
 
 
Q