user6539552
user6539552

Reputation: 1461

List Section display according to the number of items

I have tried to display a list using ForEach

ForEach(alphabet, id: \.self) { letter in

    Section(header: Text(letter).id(letter)) {
        ForEach(cats.filter(
            {
                (cat) -> Bool in
                cat.name.prefix(1) == letter
            }
        ), id: \.catId) { cat in
            NavigationLink(destination: CatDetailView()) {
                CatRow(cat: cat)
            }
        }
    }
}

I would like to only display the Section header if the filtered result is an non-empty list. How can I do that?

enter image description here

As can see in the image, Section A, C, D, ... etc has nothing. I would only like to display Section B.

Upvotes: 0

Views: 289

Answers (1)

Asperi
Asperi

Reputation: 258591

You need to do this at model level, so would be able to include sections conditionally, like

ForEach(alphabet, id:\.self) { letter in
    if viewModel.hasItems(for: letter) {
        Section(header: Text(letter).id(letter)) {
            ForEach(viewModel.items(for: letter), id:\.catId) { cat in
                NavigationLink(destination: CatDetailView()) {
                    CatRow(cat: cat)
                }
            }
        }
    }
}

Upvotes: 1

Related Questions