Swift UITableView(无节)过滤到带有节的表视图

时间:2018-09-30 19:16:23

标签: ios swift uitableview sorting uitableviewsectionheader

我在表视图中显示了一个自定义对象[Species]列表,该列表按字母顺序排序。表有一个没有标题的部分,它是一个连续的列表。

我想要实现的是,当用户选择“按国家/地区”对数据进行排序的选项时,请执行以下操作:

  • 对数组进行排序,以找出“ Species.country”需要的节数
  • 创建带有国家标题的栏目
  • 按字母顺序对国家(部分)进行排序
  • 重新加载表格视图以显示部分
  • 删除有关撤消操作的部分(将整个列表A-Z排序)

在过滤/排序时是否可以动态创建节?您能给我指出正确的方向吗?非常感谢 答:

func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 120
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.genusArr.count
}

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

    //genusArr is type of [Species]
    let genus = self.genusArr[indexPath.row]
    cell.populate(with: genus)

    return cell
}

2 个答案:

答案 0 :(得分:1)

这一切都在您的数据模型中。您始终具有带有行的节。但是您只有一个部分。修改数据模型和数据源方法以始终支持多个部分。有时候这个数据模型只有一个部分。

将数据模型更新为字典数组,其中字典包含标题和数组。顶层数组是您的部分(有时可能只是一个)。内部数组(在每个字典中)是每个部分的行。或使用标题和数组定义struct,而不使用字典。

有了这一点,并且您编写的表视图数据源和委托方法始终可以与多个节一起使用,当您碰巧只有一个节的数据时,表也可以正常工作。

现在,只需要根据需要来组织字典数组即可,这取决于您希望如何组织显示数据。

答案 1 :(得分:0)

回答节标题的问题。您可以尝试使用:

tableView(_ tableView: UITableView, titleForHeaderInSection section: Int)

tableView(tableView: UITableView, viewForHeaderInSection section: Int)