【问题标题】:How to populate UITableView with 2 sections如何用 2 个部分填充 UITableView
【发布时间】:2019-06-21 00:00:54
【问题描述】:

我的问题是 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 上获得彼此的数量……

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

【问题讨论】:

  • 我会使用字典来将这些部分映射到数据,然后您可以使用sections 数组来查找每个部分的数据,而无需检查它的值
  • 您还需要查看tableView(_:titleForHeaderInSection:) 以获得UITableViewDataSource

标签: swift uitableview sections


【解决方案1】:

每个部分都会调用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]
}

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

【讨论】:

    猜你喜欢
    • 2018-12-15
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-22
    • 1970-01-01
    • 2021-12-04
    • 1970-01-01
    相关资源
    最近更新 更多