Swift中点击UITableView单元格实现对应Section折叠的方案
点击Cell实现UITableView Section折叠的方案
嘿,我来帮你搞定这个需求!你要的是点击Section下的任意Cell就把整个Section折叠起来,核心思路是用一个状态数组追踪每个Section的展开/折叠状态,再配合TableView的数据源和代理方法来实现。下面是具体步骤:
1. 新增状态追踪数组
首先在你的ViewController里加一个布尔数组,用来记录每个Section是否处于展开状态,默认我们让所有Section一开始都是展开的:
// 针对resMenuTableView的状态数组,Addon的可以单独再建一个 var sectionExpandedStates: [Bool] = []
等你从接口拿到subCategoryModel数据之后,记得初始化这个数组:
// 接口请求成功后赋值并初始化状态数组 subCategoryModel = 你的接口返回数据 sectionExpandedStates = Array(repeating: true, count: subCategoryModel!.count) resMenuTableView.reloadData()
2. 修改行数计算逻辑
原来的numberOfRowsInSection是直接返回Cell数量,现在要根据对应Section的状态来判断——如果是折叠状态,就返回0,这样Section下的Cell就都消失了:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if tableView == resMenuTableView { // 展开状态返回实际数量,折叠返回0 return sectionExpandedStates[section] ? subCategoryModel![section].items.count : 0 } else { // 如果Addon的TableView也需要这个功能,逻辑和上面一致,记得加对应的状态数组 return AddonCategoryModel![section].addonItems.count } }
3. 处理Cell点击事件
实现didSelectRowAt代理方法,当用户点击某个Cell时,切换它所属Section的状态,然后刷新这个Section:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if tableView == resMenuTableView { // 切换当前Section的展开/折叠状态 sectionExpandedStates[indexPath.section].toggle() // 只刷新目标Section,比reloadData更高效,还能有动画 tableView.reloadSections(IndexSet(integer: indexPath.section), with: .automatic) // 可选:取消Cell的选中高亮,体验更好 tableView.deselectRow(at: indexPath, animated: true) } }
额外提示
- 如果你的AddonCategoryTableView也需要同样的折叠功能,只需要复制一套逻辑:新建
addonSectionExpandedStates数组,在拿到Addon数据后初始化,然后修改对应数据源和代理方法即可。 - 刷新时用
reloadSections而不是reloadData,既能避免整个列表闪烁,还能自带过渡动画,用户体验更好。 - 动画类型可以自己选,比如把
.automatic换成.fade或者.top,根据你的需求调整。
内容的提问来源于stack exchange,提问作者raheem
相关产品推荐
相关产品推荐

