ios - TableView 在 Swift 中展开和折叠单元格
问题描述
嗨,我看过一个关于这个问题的教程,我可以在我的表格视图中打开和关闭点击的部分,但是如果一个部分是打开的,我要打开另一个部分,我希望关闭前一个部分,但我可以不。
表视图代码
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let section = sections[section]
if section.isOpened {
return section.options.count + 1
} else {
return 1
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 0 {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "headerCell", for: indexPath) as? HeaderView else {return UITableViewCell()}
cell.backgroundColor = #colorLiteral(red: 0.9607108235, green: 0.9608257413, blue: 0.9606716037, alpha: 1)
cell.titleLabel?.text = sections[indexPath.section].title
return cell
} else {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "customCell", for: indexPath) as? CustomTableViewCell else {return UITableViewCell()}
cell.backgroundColor = #colorLiteral(red: 0.9607108235, green: 0.9608257413, blue: 0.9606716037, alpha: 1)
cell.titleLabel?.text = sections[indexPath.section].options[indexPath.row - 1]
return cell
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
sections[indexPath.section].isOpened = !sections[indexPath.section].isOpened
tableView.reloadSections([indexPath.section], with: .none)
}
剖面模型
class Section {
let title: String
let options: [String]
var isOpened: Bool = false
init(title: String, options: [String], isOpened: Bool = false) {
self.title = title
self.options = options
self.isOpened = isOpened
}
}
ViewDidLoad
sections = [
Section(title: "Spor Giyim 1", options: [1,2,3].compactMap({ return "Cell \($0)" }), isOpened: true),
Section(title: "Spor Giyim 2", options: [1,2,3].compactMap({ return "Cell \($0)" }), isOpened: false),
Section(title: "Spor Giyim 3", options: [1,2,3].compactMap({ return "Cell \($0)" }), isOpened: false),
Section(title: "Spor Giyim 4", options: [1,2,3].compactMap({ return "Cell \($0)" }), isOpened: false)
]
解决方案
您需要将它们全部重置,false
然后切换单击部分的当前状态
let toSet = !sections[indexPath.section].isOpened
sections.forEach {
$0.isOpened = false
}
sections[indexPath.section].isOpened = toSet
tableView.reloadData()
推荐阅读
- powershell - 如何打开两个运行命令然后返回用户输入的 powershell 控制台?
- java - 将媒体项添加到 MediaBrowserService
- r - R将GPS转换为带有时间戳的GPX
- php - 在 PHP 函数中返回字符串
- java - 使用 Eclipse EE 和 PostgreSQL 的登录/注册表单
- javascript - 为什么人们通常将 node_modules/.bin 内容称为“二进制文件”?
- google-bigquery - 在 Big Query 中使用 Filldown 的 Split()
- angular - 如何在Angular 5中更新另一个属性更改的属性
- r - 如何将绘图自动保存为png?
- cordova - Cordova 应用内浏览器引擎