运行时 UITableView 中的 adding/removing 个部分使用 swift

adding/removing sections in UITableView at runtime using swift

我正在尝试使用 swift

创建一个 table 具有分组样式的视图,如下图所示

我该如何处理以下问题:

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

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

谢谢,

要更新章节 headers,您只需拥有所有 header 标题的数组,然后更新该数组以包含对应章节索引的正确标题。

所以有一个实例变量类似于...

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
}

更新标题数组后,您可能想要更新或删除一个部分。为此,请使用这两种方法

func insertSections(_ sections: NSIndexSet,withRowAnimation animation: UITableViewRowAnimation)

func deleteSections(_ sections: NSIndexSet, withRowAnimation animation: UITableViewRowAnimation)

另外这个方法或许也能派上用场,

func moveSection(_ section: Int, toSection newSection: Int)