How to implement Sections dynamically on UICollectionView?

How you doing fellow developers?

I’m relatively new to iOS development and still struggling to implement what in other languages I do relatively easy.

I’m building an Events App. On my App, the user can choose which categories of events he wants to see everytime he runs the App. Sometimes according to some filters like [Date], certain categories may not have results to be shown. e.g.: He picked categories A, D, F, G and M. But for today, only D, F and M satisfies the criteria i.e. have Events to show.

So, the user preferences gives an Array of Categories (Sections). Each category should only be shown if the array of events (items in Section) for each category has at least one item. The problem is, In my UICollectionView I want to implement the numberOfSections and numberOfItemsInSection methods according to the above, with header titles, footer, etc.

Mentally I can go through the necessary logic to achieve that, like, return the count considering only those categories with at least one item. But I’m having troubles to translate it to swift code. How should I approach it? Can somebody share a code snippet implementing that?

Thanks in advance.

Upvotes: 2

Views: 959

Answers (1)

bughana
bughana

Reputation: 324

You can filter your Array of categories and then use the result as the source for the datasource functions of your collectionView.

Sample code:

// replace these structs by your actual models
struct Event {
    let id: Int
}

struct Category {
    let events: [Event]
}

// this is your Array of categories with 3 elements
let categories = [Category(events: [Event(id: 0)]), Category(events: [Event(id: 1)]), Category(events: [])]

// after filtering out the categories without events, the resulting Array has only 2 elements
let filteredCategories = categories.filter { $0.events.count > 0 }

Then you can implement the datasource functions for the collectionView like this:

func numberOfSections(in collectionView: UICollectionView) -> Int {
    return filteredCategories.count
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    let category = filteredCategories[section]
    return category.events.count
}

Upvotes: 1

Related Questions