1

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

Smart guy
  • 494
  • 6
  • 9

1 Answers1

1

Here are my assumptions about what you already have:

  1. you have a model class (Model) with a property name
  2. the data-structure behind your UICollectionView is an array of Model objects

Here's what I'd do:

  1. sort the Model array by its name property.

    sortedModels = models.sorted(by: { (first, second) -> Bool in
      return first.title.compare(second.title) == ComparisonResult.orderedAscending
    }
    
  2. 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]
    
  3. iterate through sortedList, checking the first character of the name property, then either creating a new array in the dictionary (if the key doesn't already exist) or adding the Model to an existing array

    models.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)
        }
    }
    
  4. then your numberOfSectionsInCollectionView: would return the number of keys in the dictionary

  5. and collectionView:numberOfItemsInSection: would return the number of items in the sections array
Matthew
  • 1,363
  • 11
  • 21
  • 1
    Please, just use `first.title < second.title` instead of `first.title.compare(second.title) == ComparisonResult.orderedAscending`. – Sulthan Jul 30 '17 at 11:12