使用swift在运行时在UITableView中添加/删除部分

sia*_*sia 2 runtime uitableview ios swift

我正在尝试使用swift创建一个带有分组样式的tableView,如下图所示

在此输入图像描述

我如何继续处理以下问题:

  1. 我需要在表中的运行时添加或删除Sections和CellView.第1部分即食物将始终相同,但其他剩余部分是动态添加或删除,如水果,蔬菜等.

  2. 我需要为每个新添加的部分自定义Section Header.

谢谢,

Cli*_*lip 5

要更新节标题,您只需拥有所有标题标题的数组,然后更新该数组以包含相应节标记的正确标题.

所以有一个像...一样的实例变量

var sectionHeaders: String = ["Food", "Fruit", "Vegetables"]

然后实现此方法:

override func tableView(tableView: UITableView!, viewForHeaderInSection section: Int) -> UIView! {

    var label : UILabel = UILabel()
    label.text = self.sectionHeaders[section]
    return label
}
Run Code Online (Sandbox Code Playgroud)

更新标题数组后,您将要更新或删除节.为此,请使用这两种方法

func insertSections(_ sections: NSIndexSet,withRowAnimation animation: UITableViewRowAnimation)
Run Code Online (Sandbox Code Playgroud)

func deleteSections(_ sections: NSIndexSet, withRowAnimation animation: UITableViewRowAnimation)
Run Code Online (Sandbox Code Playgroud)

这种方法也可以派上用场,

func moveSection(_ section: Int, toSection newSection: Int)
Run Code Online (Sandbox Code Playgroud)