UITableView切换自定义Cell类与数据源异常:仅能切换一次无法返回
解决UITableView切换数据源/Cell无法来回切换的问题
看起来你遇到的核心问题是切换一次后,UITableView没有正确响应displayMode的后续变化,大概率是你的UITableView数据源方法(比如cellForRowAt、numberOfRowsInSection)没有根据当前的displayMode动态返回对应的数据和Cell类型。我给你一步步梳理解决方案:
1. 先确保基础配置没问题
首先确认你已经正确定义了两个数据源,并且给UITableView设置了正确的delegate和dataSource:
// 假设你的数据源类型,根据实际业务调整 var dataSource1: [YourModelType] = [] // 对应模式1的数据源 var dataSource2: [YourModelType] = [] // 对应模式2的数据源 override func viewDidLoad() { super.viewDidLoad() // 绑定数据源和代理 myTable.dataSource = self myTable.delegate = self // 如果是代码注册Cell,记得注册两个自定义Cell类 myTable.register(CustomCell1.self, forCellReuseIdentifier: "CustomCell1") myTable.register(CustomCell2.self, forCellReuseIdentifier: "CustomCell2") // 初始化数据源数据... }
2. 简化切换按钮的逻辑
你的按钮点击逻辑可以简化,确保每次点击都能正确切换displayMode并刷新表格:
var displayMode: Int = 1 @objc func tappedButton(_ sender: UIButton?) { // 切换模式 displayMode = displayMode == 1 ? 2 : 1 // 可选:更新按钮标题,让用户知道当前模式 sender?.setTitle(displayMode == 1 ? "切换到模式2" : "切换到模式1", for: .normal) // 强制刷新表格 myTable.reloadData() // 可以加个打印,确认模式确实切换了 print("当前模式:\(displayMode)") }
3. 关键:数据源方法要动态响应displayMode
这是最容易出错的地方!你必须在所有数据源方法里,根据当前的displayMode返回对应的数据和Cell:
(1)返回行数
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // 根据当前模式返回对应数据源的行数 return displayMode == 1 ? dataSource1.count : dataSource2.count }
(2)返回对应Cell
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if displayMode == 1 { // 复用模式1的自定义Cell let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell1", for: indexPath) as! CustomCell1 // 用dataSource1的数据配置Cell let model = dataSource1[indexPath.row] cell.configure(with: model) // 假设你有配置Cell的方法 return cell } else { // 复用模式2的自定义Cell let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell2", for: indexPath) as! CustomCell2 // 用dataSource2的数据配置Cell let model = dataSource2[indexPath.row] cell.configure(with: model) return cell } }
4. 排查其他可能的问题
- 如果用的是Storyboard/XIB创建的Cell,确保两个Cell的
Identifier和代码里的字符串完全一致; - 检查
displayMode是否被其他地方意外修改(比如在数据源方法里不小心赋值了); - 如果切换后表格没变化,先看打印的
displayMode是否正确切换,再检查数据源方法里的判断逻辑有没有写错。
按照这个流程调整后,应该就能实现来回切换的效果了!
内容的提问来源于stack exchange,提问作者Almazini
相关产品推荐
相关产品推荐

