I have a list of names sorted alphabetically, and now I want display these names in a table view. I'm struggling with grouping these names for each letter.
My code looks like this:
class ContactTableViewController: UITableViewController {
var contactArray = ["Alan Douglas", "Bob", "Bethany Webster", "Casey Fleser", "Daniel Huckaby", "Michael Morrison"]
var contactSection = [String]()
var contactDictionary = [String : [String]]()
override func viewDidLoad() {
super.viewDidLoad()
generateWordsDict()
let nav = self.navigationController?.navigationBar
nav?.tintColor = UIColor(red: 16.0, green: 18.0, blue: 34.0, alpha: 1.0)
nav?.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func generateWordsDict(){
for contact in contactArray {
let key = "\(contact[contact.startIndex])"
let lower = key.lowercased()
if var contactValue = contactDictionary[lower]
{
contactValue.append(contact)
}else{
contactDictionary[lower] = [contact]
}
}
contactSection = [String](contactDictionary.keys)
contactSection = contactSection.sorted()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return contactSection.count
}
override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
return contactSection[section]
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let contactKey = contactSection[section]
if let contactValue = contactDictionary[contactKey]{
return contactValue.count
}
return 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellContact", for: indexPath)
let cotactkey = contactSection[indexPath.section]
if let contactValue = contactDictionary[cotactkey.lowercased()] {
cell.textLabel?.text = contactArray[indexPath.row]
cell.textLabel?.textColor = UIColor.white
}
return cell
}
override func sectionIndexTitles(for tableView: UITableView) -> [String]? {
return contactSection
}
override func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
guard let index = contactSection.index(of: title) else {
return -1
}
return index
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.tableView.deselectRow(at: indexPath, animated: true)
}
}
and it all works pretty good except for the grouping which makes my table view end up like this:
I wanted to do something like this:
but I do not know how to implement:
How to adjust the color of the letters? how to make a list of names to display correctly?