gpt4 book ai didi

arrays - 如何使用 sectionIndexTitles 的不同数组填充索引 UITableView 的部分

转载 作者:行者123 更新时间:2023-11-28 11:33:29 26 4
gpt4 key购买 nike

我正在使用一组人名来加载表格。我想根据每个人的居住州分开这些部分,同时将 sectionIndexTitles 限制为州名的第一个字母。我的 sectionIndexTitles 将是 ["A"、"C"、"D"、"F"、"G"、"H"、"I"、"K"、"L"、"M"、"N"、 “O”、“P”、“R”、“S”、“T”、“U”、“V”、“W”],而表格部分将分为所有 50 个状态。

本质上,字母 A(索引 0)属于阿拉斯加、阿拉巴马州、阿肯色州和亚利桑那州。没有 B,所以下一个字母 C(索引 2)应该滚动到 California,其部分数为 4。

我遇到的问题是这些部分显然没有正确索引,因此当点击字母 A 以外的任何索引标题时,表格 View 不会滚动到正确的字母。

最佳答案

按州名称对人员数组进行分组,并从字典中创建元组数组。然后在 tableview 数据源方法中使用该数组

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
struct Person {
var name: String
var state: String
}
var allPeople = [Person]()
var groupedPeople = [(state:String, people:[Person])]()
@IBOutlet weak var tableView: UITableView!

override func viewDidLoad() {
super.viewDidLoad()

allPeople = [Person(name: "a", state: "Alaska"), Person(name: "x", state: "Florida"),
Person(name: "c", state: "California")]
groupedPeople = Dictionary(grouping: allPeople, by: { $0.state }).sorted(by: { $0.key < $1.key })
.map({ (state:$0.key, people:$0.value)
})
}
func sectionIndexTitles(for tableView: UITableView) -> [String]? {
return Array(Set(groupedPeople.map({ String($0.state.first!) })))
}
func numberOfSections(in tableView: UITableView) -> Int {
return groupedPeople.count
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return groupedPeople[section].state
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return groupedPeople[section].people.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") ?? UITableViewCell(style: .subtitle, reuseIdentifier: "cell")
cell.textLabel?.text = groupedPeople[indexPath.section].people[indexPath.row].name
cell.detailTextLabel?.text = groupedPeople[indexPath.section].people[indexPath.row].state
return cell
}
}

更新

当你有比 sectionIndexTitles 多的部分时,你应该实现 sectionForSectionIndexTitle方法并返回适当的部分索引。

func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
if let index = groupedPeople.firstIndex(where: { $0.state.hasPrefix(title) }) {
return index
}
return 0
}

关于arrays - 如何使用 sectionIndexTitles 的不同数组填充索引 UITableView 的部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56258941/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com