Skip to content

Add support for Group(subviews:), Group(sections:), ForEach(subviews:), and ForEach(sections:) #401

@marcelofabri

Description

@marcelofabri

ViewInspector currently doesn't know to handle Group(subviews:), which creates a GroupElementsOfContent view.

Here's a test that currently fails:

func testGroupSubviews() throws {
    let containerView = HStack {
        Text("First")
        Text("Second") 
        Text("Third")
    }
    
    let view = Group(subviews: containerView) { subviews in
        ForEach(Array(subviews.enumerated()), id: \.offset) { index, subview in
            subview
                .accessibilityIdentifier("subview-\(index)")
        }
    }

    let inspectedGroup = try view.inspect().group()
    XCTAssertNotNil(inspectedGroup)

    _ = try inspectedGroup.find(viewWithAccessibilityIdentifier: "subview-1")
}

I tried implementing it by looking at some of the existing examples (mainly ForEach) but I'm stuck. Here's what I've got so far:

@available(iOS 18.0, macOS 15.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
extension ViewType.GroupElementsOfContent: MultipleViewContent {

    public static func children(_ content: Content) throws -> LazyGroup<Content> {
        let provider = try Inspector.cast(value: content.view, type: MultipleViewProvider.self)
        let children = try provider.views()
        return LazyGroup(count: children.count) { index in
            try Inspector.unwrap(view: try children.element(at: index),
                                 medium: content.medium.resettingViewModifiers())
        }
    }
}

@available(iOS 18.0, macOS 15.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
extension GroupElementsOfContent: MultipleViewProvider {
    func views() throws -> LazyGroup<Any> {
        typealias Builder = (SwiftUI.SubviewsCollection) -> Content
        let builder = try Inspector
            .attribute(label: "content", value: self, type: Builder.self)
        let subviews = try Inspector
            .attribute(path: "storage|view", value: self, type: Subviews.self)
        
        // how can I use this?? `builder` requires a `SubviewsCollection` and it's initializer is not public 
    }
}

Any pointers would be very appreciated. Thanks!

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions