This question has previously been posted, like Alphabetical sections in table table view in swift, but I can't really wrap my head around it when I try to implement it into my own code.
I have the standard functions to get the alphabetic sections in place:
func numberOfSections(in tableView: UITableView) -> Int {
return collation.sectionTitles.count
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return collation.sectionTitles[section]
}
func sectionIndexTitles(for tableView: UITableView) -> [String]? {
return collation.sectionIndexTitles
}
func tableView(tableView: UITableView!, sectionForSectionIndexTitle title: String!, atIndex index: Int) -> Int {
return collation.section(forSectionIndexTitle: index)
}
I have an array that has collected data from the local contact book on the app: var contactArray = [ExternalAppContactsBook]()
. ExternalAppContactsBook
looks like this:
class ExternalAppContactsBook {
var firstName = ""
var lastName = ""
var phoneNumber = ""
var company = ""
}
I would like to list the object in alphabetical order based on lastName
under their respective sections. I get that the magic happens in cellForRowAt
but I can't seem to get it right. The article above maps a string to a dictionary, but I need an object, which complicates things.
I have mapped a dictionary
by breaking out lastName
from the object
into its own array
like this:
var lastNameArray = [String]()
for index in self.contactArray {
lastNameArray.append(index.lastName)
}
let groupedDictionary = Dictionary(grouping: lastNameArray, by: {String($0.prefix(1))})
let keys = groupedDictionary.keys.sorted()
var mapedSection = [Section]()
mapedSection = keys.map{Section(letter: $0, names: groupedDictionary[$0]!.sorted())}
But how do I use it?
Could someone give me a few pointers to get started?
EDIT
It works this way, but I'm unsure if it's gonna work to arrange the object in the tableview
:
for index in self.contactArray {
lastNameArray.append(index.lastName)
}
if let c = self.contactArray {
let groupedDictionary = Dictionary(grouping: lastNameArray, by: {String($0.prefix(1))})
let keys = groupedDictionary.keys.sorted()
var mapedSection = [Section]()
mapedSection = keys.map{Section(letter: $0, names: groupedDictionary[$0]!.sorted())}
print("☎️", mapedSection)
}
The print shows:
Section(letter: "H", names: ["Haro", "Higgins"]), Section(letter: "T", names: ["Taylor"])
...and so on. I think there still might be a problem when actually populating the tableView
.