UITableView多组单选功能异常求助:单组正常多组失效
解决UITableView多Section独立单选的问题
嘿,我来帮你搞定这个多Section单选的问题!你的核心问题在于只用了一个selectedIndexPath变量来记录选中状态,这显然没法区分不同Section的选中情况——所以当你选了Section1的Row0时,Section2的Row0也会被误判选中,因为你原来的判断逻辑只处理了Section0,其他Section的判断完全没跟上。
咱们换个思路,用字典来存储每个Section对应的选中Row,这样每个Section的选中状态就独立了。下面是具体的修改步骤:
1. 替换选中状态的存储变量
把原来单个的selectedIndexPath换成一个字典,用Section编号作为key,对应选中的Row编号作为value:
var selectedRowsBySection: [Int: Int] = [:] // 存储每个Section的选中Row
2. 重构cellForRowAt的判断逻辑
原来的代码只针对Section0做了判断,现在要改成根据当前Section对应的选中Row来设置图片状态:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "你的Cell标识符", for: indexPath) // 默认设置为未选中状态的图片 cell.imageView?.image = UIImage(named: "radio1") // 检查当前Section是否有选中的Row if let selectedRow = selectedRowsBySection[indexPath.section], selectedRow == indexPath.row { // 如果当前行是该Section选中的Row,切换为选中状态图片 cell.imageView?.image = UIImage(named: "radio2") } return cell }
这里要注意:你原来设置的tag其实没必要,我们直接通过indexPath就能精准定位到行,不用依赖tag来判断。
3. 更新didSelectRowAt的选中逻辑
点击行时,把当前Section对应的选中Row更新到字典里,然后刷新TableView使状态生效:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // 记录当前Section选中的Row selectedRowsBySection[indexPath.section] = indexPath.row // 刷新TableView,让所有行的状态同步更新 tableView.reloadData() // (可选优化)如果想提升性能,可以只刷新当前Section和之前选中行所在的Section,避免全量刷新: // if let prevSection = selectedRowsBySection.keys.first(where: { $0 != indexPath.section }), let prevRow = selectedRowsBySection[prevSection] { // tableView.reloadRows(at: [IndexPath(row: prevRow, section: prevSection), indexPath], with: .automatic) // } else { // tableView.reloadRows(at: [indexPath], with: .automatic) // } }
可选:设置默认选中行
如果需要某个Section默认选中某一行,只需在初始化字典时添加对应值即可:
// 比如默认选中Section0的Row0,Section1的Row1 selectedRowsBySection[0] = 0 selectedRowsBySection[1] = 1
这样修改后,每个Section的单选状态就完全独立了,选Section1的Row0不会影响其他Section的任何行,完美解决你的问题!
内容的提问来源于stack exchange,提问作者Naresh
相关产品推荐
相关产品推荐

