I store strings of a view controller in a string array. I import this string array as a Data Source in my table view. This all works smoothly. But now I would like to sort the table view and add section headers. The section header should be from the alphabet, the rows of the meaning sections should be all strings from the array, starting with the letter of the section header.
I know how I can achieve this with static arrays. But how can I make it that only the sections are shown, which also have rows(strings in the array)? And how can I make it so that it generates a new section when saving a new string with a letter, which does not yet exist in the sections?
I hope I have explained it accurately enough. I tried for a long time to solve this problem. It would be great if someone could help me.
Here are some code snippets:
class OverViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var addButton: UIBarButtonItem!
@IBOutlet weak var editButton: UINavigationItem!
var kontaktListe = Telefonbuch.loadArray()
var sections = [[String]]()
var collation = UILocalizedIndexedCollation.currentCollation()
override func viewDidLoad()
{
super.viewDidLoad()
tableView.dataSource = self
configureSectionData()
tableView.reloadData()
}
func configureSectionData()
{
let names = kontaktListe.map{$0.name}
let selector: Selector = "description"
sections = Array(count:collation.sectionTitles.count, repeatedValue: [])
let sortedObjects = collation.sortedArrayFromArray(names, collationStringSelector: selector)
for object in sortedObjects {
let sectionNumber = collation.sectionForObject(object, collationStringSelector: selector)
sections[sectionNumber].append(object as! String)
}
}
I load the object var kontaktListe = Telefonbuch.loadArray()
and get the name property let names = kontaktListe.map{$0.name}
. And there I would like to get the strings to sort and add from.