首页 > 解决方案 > 如何用 2 个部分填充 UITableView

问题描述

我的问题是 NumberOfRowsInSection 应该读取两个值。

let sections = ["Apples", "Oranges"]
override func numberOfSections(in tableView: UITableView) -> Int {
        return sections.count
    }



override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {


//Option A)
        if apples.count & oranges.count != 0 {
           return apples.count & oranges.count
        } else {
            return 0
        }

//Option B)

        if sections[0] == "Apples" {
            return apples.count
        }

        if sections[1] == "Oranges"{
            return oranges.count
        }
        return 0
    }

所有选项都不起作用,崩溃是因为它没有得到彼此的数量……在 CellForRowAt 上。

另外有人知道如何获得这些部分的标题吗?

标签: swiftuitableviewsections

解决方案


numberOfRows将为每个部分调用,因此您需要根据正在查询的当前部分返回正确的值:

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return section == 0 ? apples.count : oranges.count
}

cellForRowAt您需要在所有其他数据源/委托方法中使用类似的模式:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", indexPath: indexPath
    if indexPath.section == 0 {
        cell.titleLabel.text = apples[indexPath.row]
    } else {
        cell.titleLabel.text = oranges[indexPath.row]
    }

    return cell
}

这被简化并做了很多假设,但它给了你正确的想法。

对于标题,您需要:

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

这个答案还假设您只有基于两个数组变量的两个部分。这远非理想。你真的应该有一个具有所有正确结构的单一数据结构。那么不需要做任何假设。您可以添加更多部分和行,而不必更改任何表格视图代码。


推荐阅读