索引表视图

时间:2018-10-30 20:45:01

标签: ios swift tableview

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

 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。有人可以解释吗?预先谢谢你。

1 个答案:

答案 0 :(得分:1)

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

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

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

carSectionTitles = carsDictionary.keys.sorted()

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

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
相关问题