点击UITableView指定cell时如何单独修改对应cell的高度?
问题根源
你当前的expandedIndexSet存储的是section的索引,高度判断逻辑也是只要当前行所属section在展开集合里,就返回大高度,自然会触发整个section所有cell高度同步变化。
修复方案
把存储展开状态的集合从存section的IndexSet改为存具体行的Set<IndexPath>,仅对匹配到的被点击行返回大高度即可,修复后代码如下:
// 替换原有的IndexSet,存储所有已展开cell对应的IndexPath var expandedIndexPaths: Set<IndexPath> = [] func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { // 仅当前点击的indexPath在展开集合中时返回大高度 if expandedIndexPaths.contains(indexPath) { return 406 } else { return 88 } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) if expandedIndexPaths.contains(indexPath) { expandedIndexPaths.remove(indexPath) } else { // 如果需要同一时间仅展开一个cell,可打开下面两行注释 // expandedIndexPaths.removeAll() // tableView.reloadData() expandedIndexPaths.insert(indexPath) } tableView.reloadRows(at: [indexPath], with: .automatic) }
注意事项
- 如果你的cell内部子控件需要适配展开/收起状态,需要在
cellForRowAt方法里根据expandedIndexPaths.contains(indexPath)的状态主动更新UI,避免cell重用时出现布局错乱。
内容的提问来源于stack exchange,提问作者islahulislam.ca
相关产品推荐
相关产品推荐

