如何从对象中获取按字母顺序排列的 tableView 部分

How do I get alphabetic tableView sections from an object

这个问题之前已经发布过,例如 ,但是当我尝试将它实现到我自己的代码中时,我无法真正理解它。

我有标准函数来放置字母部分:

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)
}

我有一个数组,它从应用程序的本地通讯录中收集数据:var contactArray = [ExternalAppContactsBook]()ExternalAppContactsBook 看起来像这样:

class ExternalAppContactsBook {
    var firstName = ""
    var lastName = ""
    var phoneNumber = ""
    var company = ""
}

我想在各自的部分下根据 lastName 的字母顺序列出对象。我知道魔术发生在 cellForRowAt 中,但我似乎无法正确理解。上面的文章将字符串映射到字典,但我需要一个对象,这使事情变得复杂。

我通过将 lastNameobject 分解成它自己的 array 来映射 dictionary,如下所示:

var lastNameArray = [String]()

for index in self.contactArray {
    lastNameArray.append(index.lastName)
}

let groupedDictionary = Dictionary(grouping: lastNameArray, by: {String([=12=].prefix(1))})
let keys = groupedDictionary.keys.sorted()
var mapedSection = [Section]()
mapedSection = keys.map{Section(letter: [=12=], names: groupedDictionary[[=12=]]!.sorted())}

但是我该如何使用呢?

有人可以给我一些入门指导吗?

编辑 它以这种方式工作,但我不确定是否可以在 tableview:

中安排对象
for index in self.contactArray {
    lastNameArray.append(index.lastName)
}

if let c = self.contactArray {
    let groupedDictionary = Dictionary(grouping: lastNameArray, by: {String([=13=].prefix(1))})
    let keys = groupedDictionary.keys.sorted()
    var mapedSection = [Section]()
    mapedSection = keys.map{Section(letter: [=13=], names: groupedDictionary[[=13=]]!.sorted())}
    print("☎️", mapedSection)
}

打印显示:

Section(letter: "H", names: ["Haro", "Higgins"]), Section(letter: "T", names: ["Taylor"])

...等等。我认为实际填充 tableView.

时仍然可能存在问题

你要分组contactArraysections(这个名字就够了)必须成为数据源数组

var sections = [Section]()

你必须声明 Section

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

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

根据我在链接问题中的回答,数据源和委托方法是

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{[=13=].letter}
}

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return sections[section].letter
}