How do I get alphabetic tableView sections from an object

好久不见. 提交于 2019-12-06 14:54:12

You have to group contactArray and sections (this name is sufficient) must become the data source array

var sections = [Section]()

and you have to declare Section

struct Section {
    let letter : String
    let people : [ExternalAppContactsBook]
}

let groupedDictionary = Dictionary(grouping: contactArray, by: {String($0.lastName.prefix(1))})
let keys = groupedDictionary.keys.sorted()
sections = keys.map{Section(letter: $0, people: groupedDictionary[$0]!.sorted(by: {$0.lastName < $1.lastName})}

According to my answer in the linked question the datasource and delegate methods are

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return sections[section].people.count
}

func numberOfSectionsInTableView(tableView: UITableView) -> Int{
    return sections.count
}

func sectionIndexTitles(for tableView: UITableView) -> [String]? {
    return sections.map{$0.letter}
}

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return sections[section].letter
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!