我使用UITableViewController
尝试返回一系列数据,每个数据都有自己的可折叠部分,类似于下面的内容。
示例表视图控制器
我分别添加了两个单独的标题部分("项目1"(和("项目2"(;正在返回并可供选择,而"项目";部分未出现。
这是我用来显示部分的代码:
var tableViewData = [cellData]()
self.tableViewData = [cellData(opened: false, title: "Item 1", sectionData: [productName1 ?? "test?"])]
self.tableViewData = [cellData(opened: false, title: "Item 2", sectionData: [productName2 ?? "test"])]
以下是我用来以编程方式更改节的代码(更新每个节下的结果数(。
override func numberOfSections(in tableView: UITableView) -> Int {
return tableViewData.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableViewData[section].opened == true {
return tableViewData[section].sectionData.count + 1
} else {
return 1
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var dataIndex = indexPath.row - 1
if indexPath.row == 0 {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "cell") else {return UITableViewCell()}
cell.textLabel?.text = tableViewData[indexPath.section].title
return cell
} else {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "cell") else {return UITableViewCell()}
cell.textLabel?.text = tableViewData[indexPath.section].sectionData[indexPath.row - 1]
return cell
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.row == 0 {
if tableViewData[indexPath.section].opened == true {
tableViewData[indexPath.section].opened = false
let sections = IndexSet.init(integer: indexPath.section)
tableView.reloadSections(sections, with: .none)
} else {
tableViewData[indexPath.section].opened = true
let sections = IndexSet.init(integer: indexPath.section)
tableView.reloadSections(sections, with: .none)
}
}
}
为什么在应用程序运行后,只有一个可选部分出现,而添加了两个("项目1"one_answers"项目2"?请在下面的应用程序屏幕截图中找到页面当前外观的视觉示例。
应用内演示图像
您实际上并没有添加两个部分——您添加了一个项目,然后用另一个替换了它:
var tableViewData = [cellData]()
self.tableViewData = [cellData(opened: false, title: "Item 1", sectionData: [productName1 ?? "test?"])] //this is the first assignment
self.tableViewData = [cellData(opened: false, title: "Item 2", sectionData: [productName2 ?? "test"])] //then, you overwrite it here
相反,你可以这样做:
self.tableViewData =
[cellData(opened: false, title: "Item 1", sectionData: [productName1 ?? "test?"]),
cellData(opened: false, title: "Item 2", sectionData: [productName2 ?? "test"])]