通过Delegate实现ViewController向TableView回传数据后列表不更新怎么办?
问题根源
editContact回调方法中声明的var contact:Contact?是局部空可选值,未关联到原有contacts数据源数组中的目标对象,基于可选链的赋值操作在对象为nil时不会实际执行,数据源没有被修改。- 点击Cell跳转时没有记录当前选中的联系人索引,回调触发后无法定位到需要修改的数组对应位置的条目。
- 即使数据源修改成功,没有主动触发TableView的刷新接口,界面不会同步更新数据。
修复步骤
- 在
SecondViewController主类中新增属性存储选中的索引:
// 新增属性记录当前选中的联系人下标 var selectedContactIndex: Int?
- 修改
didSelectRowAt方法,跳转时存储选中的索引:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // 记录选中的索引 selectedContactIndex = indexPath.row let newVC = NewViewController() newVC.nameLabel.text = contacts[indexPath.row].name newVC.delegate = self newVC.numberPhoneLabel.text = contacts[indexPath.row].numberPhone newVC.avatarView.image = contacts[indexPath.row].avatar self.navigationController?.pushViewController(newVC, animated: true) }
- 重写
editContact回调方法,修改数据源并刷新列表:
func editContact(name: String, numberPhone: String) { // 校验索引合法性 guard let index = selectedContactIndex, contacts.indices.contains(index) else { return } // 直接修改数据源数组对应位置的联系人信息 contacts[index].name = name contacts[index].numberPhone = numberPhone // 局部刷新对应行,性能更优 tableView.reloadRows(at: [IndexPath(row: index, section: 0)], with: .automatic) // 也可使用全量刷新:tableView.reloadData() }
内容的提问来源于stack exchange,提问作者Lực Lê Gia
相关产品推荐
相关产品推荐

