admin管理员组

文章数量:1386710

accessibilityIdentifier is getting added multiple times when added inside for loop.
Below is my code

class viewModel {
    var availableSectionWithElements: [String: [String]]? = ["fruits" : ["Mangoes", "bananas"], "veg": ["Tomato", "carrots"]]
}

Struct mainView {
    VStack {
        ForEach(viewModel.availableSectionWithElements.indices, id: \.self) { index in
            let sectionTitle = viewModel.availableSectionWithElements[index].title
            Section {
                ForEach(viewModel.availableSectionWithElements[index].elements, id: \.self) { item in
                    NavigationLink(value: item) {
                        CellView(viewModel: viewModel.moreCellViewModel(element: item))
                            .accessibilityIdentifier("k")
                    }
                }
            }
        header: {
            MoreHeaderView(title: sectionTitle)
                .accessibilityIdentifier("\(HeaderView.self)\(index)")
        }
        }
    }
}

My accessbilityIdentifier is k-k-k when seen in Accessibility Inspector.

How to make sure to add accessibility identifier only once per view?

accessibilityIdentifier is getting added multiple times when added inside for loop.
Below is my code

class viewModel {
    var availableSectionWithElements: [String: [String]]? = ["fruits" : ["Mangoes", "bananas"], "veg": ["Tomato", "carrots"]]
}

Struct mainView {
    VStack {
        ForEach(viewModel.availableSectionWithElements.indices, id: \.self) { index in
            let sectionTitle = viewModel.availableSectionWithElements[index].title
            Section {
                ForEach(viewModel.availableSectionWithElements[index].elements, id: \.self) { item in
                    NavigationLink(value: item) {
                        CellView(viewModel: viewModel.moreCellViewModel(element: item))
                            .accessibilityIdentifier("k")
                    }
                }
            }
        header: {
            MoreHeaderView(title: sectionTitle)
                .accessibilityIdentifier("\(HeaderView.self)\(index)")
        }
        }
    }
}

My accessbilityIdentifier is k-k-k when seen in Accessibility Inspector.

How to make sure to add accessibility identifier only once per view?

Share Improve this question edited Mar 18 at 0:26 soundflix 2,86512 gold badges16 silver badges34 bronze badges asked Mar 17 at 15:13 AppleDeveloperAppleDeveloper 1,4593 gold badges21 silver badges52 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

Instead of giving each CellView the same identifier "k", use some unique value like this:

...
CellView(viewModel: viewModel.moreCellViewModel(element: item))
    .accessibilityIdentifier("Cell_\(item)")
...

本文标签: iosHow to make sure to add accessibility identifier only once per view in SwiftUIStack Overflow