gpt4 book ai didi

ios - 索引 TableView

转载 作者:行者123 更新时间:2023-11-28 14:05:14 24 4
gpt4 key购买 nike

我是 Swift 的初学者,我尝试根据本教程制作一个 Indexed table view:https://www.ioscreator.com/tutorials/indexed-table-view-ios-tutorial-ios11 ,但有些疑惑,想请教一下。到目前为止,这是我的代码:

 for car in cars {
let carKey = String(car.prefix(1))
if var carValues = carsDictionary[carKey] {
carValues.append(car)
carsDictionary[carKey] = carValues
} else {
carsDictionary[carKey] = [car]
}
}

// 2
carSectionTitles = [String](carsDictionary.keys)
carSectionTitles = carSectionTitles.sorted(by: { $0 < $1 })

首先,我想确定这一行

if var carValues = carsDictionary[carKey]

carsDictionary 中获取所有以 word(carKey) 开头的汽车并存储到数组中。如果为真,则将下一辆车存储到数组中,并将其放回字典中。是否正确?

不幸的是我不明白这条线在做什么

carSectionTitles = [String](carsDictionary.keys)

此外,我对这个功能不太确定,主要是“配置单元”部分

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// 3
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)

// Configure the cell...
let carKey = carSectionTitles[indexPath.section]
if let carValues = carsDictionary[carKey] {
cell.textLabel?.text = carValues[indexPath.row]
}

return cell
}

它像循环一样工作吗?我不确定 indexPath.section。有人可以解释一下吗?提前谢谢你。

最佳答案

创建字典的方法是正确的,但在 Swift 4 中有更方便的方法

carsDictionary = Dictionary(grouping: cars, by: {$0.prefix(1)})

carSectionTitles = [String](carsDictionary.keys) 行创建了一个字典键(前缀字母)数组。排序数组的这一行和下一行可以写成更高效的方式:

carSectionTitles = carsDictionary.keys.sorted()

IndexPath 有两个组成部分,sectionrow。这些部分由 carSectionTitles 表示,字典中的键和行是字典中的值。 cellForRowAt 为每一行调用一次。该代码从 carSectionTitles 获取部分并从字典中获取行。可选绑定(bind)实际上是不需要的,因为它保证每个字母都有一个关联的数组。

let carKey = carSectionTitles[indexPath.section] // carKey is one of the prefix letters
let carValues = carsDictionary[carKey]! // get the rows
cell.textLabel?.text = carValues[indexPath.row] // get the value for that particular row

关于ios - 索引 TableView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53072652/

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