I have a list of names in an array, I want to display them on a collection view in alphabetical order. And also to show the alphabet for each of the section how can I achieve this. Click here for Image
Asked
Active
Viewed 652 times
1 Answers
1
Here are my assumptions about what you already have:
- you have a model class (
Model
) with a propertyname
- the data-structure behind your
UICollectionView
is an array ofModel
objects
Here's what I'd do:
sort the
Model
array by itsname
property.sortedModels = models.sorted(by: { (first, second) -> Bool in return first.title.compare(second.title) == ComparisonResult.orderedAscending }
create a new property to hold the UICollectionView data, where the dictionary key is a single letter ("A", for example), and an array of section names which will contain the sections in the correct order. This will be the section title in the collection view
var data = Dictionary<Character, [Model]>() var sections = [Character]
iterate through
sortedList
, checking the first character of thename
property, then either creating a new array in the dictionary (if the key doesn't already exist) or adding theModel
to an existing arraymodels.forEach { (model) in let firstCharacter = model.name.characters.first! if var array = data[firstCharacter] { array.append(model) data[firstCharacter] = array } else { var array = [Model]() array.append(model) data[firstCharacter] = array sections.append(firstCharacter) } }
then your
numberOfSectionsInCollectionView:
would return the number of keys in the dictionary- and
collectionView:numberOfItemsInSection:
would return the number of items in the sections array

Matthew
- 1,363
- 11
- 21
-
1Please, just use `first.title < second.title` instead of `first.title.compare(second.title) == ComparisonResult.orderedAscending`. – Sulthan Jul 30 '17 at 11:12