【发布时间】:2019-10-15 14:54:22
【问题描述】:
这个问题之前已经发布过,比如Alphabetical sections in table table view in swift,但是当我尝试将它实现到我自己的代码中时,我真的无法理解它。
我有标准函数来获取字母部分:
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,但我似乎无法正确处理。上面的文章将字符串映射到字典,但我需要一个对象,这使事情变得复杂。
我通过将lastName 从object 拆分为自己的array 来映射dictionary,如下所示:
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())}
但是我该如何使用它呢?
有人可以给我一些指导吗?
编辑
它以这种方式工作,但我不确定在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)
}
打印显示:
Section(字母:“H”,名称:[“Haro”,“Higgins”]),Section(字母:“T”,名称:[“Taylor”])
...等等。我认为实际填充tableView 时可能仍然存在问题。
【问题讨论】:
标签: swift uitableview sections