求助:如何点击TableView末尾分区的+按钮添加新行?
解决TableView点击+按钮添加新行的问题
我看了你的代码,发现几个关键问题导致点击+按钮没法正确添加新行,咱们一步步来修正:
问题分析
- 数据源不匹配:你分区0的行数是基于
others.count计算的,但点击按钮时却往data数组里添加数据——这两个数组没有关联,TableView根本不知道要新增行。 - 冗余的选中状态处理:点击添加按钮的逻辑里,你错误地操作了
selectedIndexes还调用了reloadRows,这完全是多余的,反而会干扰正常的插入操作。 - 不必要的indexPath获取:这个+按钮固定在分区1的第0行,不需要通过按钮位置去获取indexPath,绕圈的操作容易出问题。
修正后的代码
1. 修正添加按钮的点击方法
把数据源统一为others数组(假设你用这个数组管理分区0的用户数据),直接添加新数据并插入行:
@objc func addButtonClicked(sender:UIButton) { // 假设你的数据模型是类似这样的,根据实际情况调整 let newGuest = GuestModel(firstname: "Guest", lastname: "\(others.count + 1)") others.append(newGuest) // 插入新行到分区0的最后位置 let newIndexPath = IndexPath(row: others.count - 1, section: 0) tableView.insertRows(at: [newIndexPath], with: .automatic) }
2. 简化Cell的按钮设置
因为+按钮的功能是固定的添加操作,不需要设置tag,直接绑定事件即可:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.section == 0 { let cell = tableView.dequeueReusableCell(withIdentifier: "ShareCell", for: indexPath) as! SelectOthersTableViewCell cell.firstName.text = others[indexPath.row].firstname cell.lastName.text = others[indexPath.row].lastname return cell } else { let cell = tableView.dequeueReusableCell(withIdentifier: "addCell", for: indexPath) as! addTableCell // 移除多余的tag设置,直接绑定点击事件 cell.addCells.addTarget(self, action: #selector(addButtonClicked(sender:)), for: .touchUpInside) return cell } }
3. 确保数据源初始化正确
在ViewController的初始化部分,确保others数组是初始化好的空数组:
var others: [GuestModel] = [] // 替换成你实际的数据模型类型
验证效果
这样修改后,点击分区1的+按钮,就会往others数组里添加新的Guest数据,TableView会自动在分区0的末尾插入新行,动画效果也会正常显示。
内容的提问来源于stack exchange,提问作者Irwan Madness
相关产品推荐
相关产品推荐

