Swift中为UITableView Cell设置字符串标识符并点击取值问题求解
问题根因
- 现有代码没有从你存储标识符的数据源数组中读取对应选中行的内容,仅重复做了两次Cell实例的可选绑定,且内部声明的
cellPressed是局部变量,赋值逻辑是取当前已有的self.cellPressedId,完全没有关联选中行的信息,才会出现每次都拿到最后一个值的问题。 - 不需要额外给Cell绑定专属标识,UITableView标准的取值逻辑是直接通过选中行的
indexPath.row从数据源数组取对应下标的元素即可,性能更高也不会出现Cell复用导致的取值错误问题。
正确实现
首先确保你已经声明了存储标识符的数据源数组,示例如下:
// 存储每个Cell对应标识符的数据源数组,根据你的业务需求填充内容 let cellIdentifierList: [String] = ["id_0", "id_1", "id_2"]
修改didSelectRowAt方法的实现:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // 直接从数据源取对应行的标识符,赋值给全局变量 self.cellPressedId = cellIdentifierList[indexPath.row] // 可选:取消选中状态,符合大部分交互规范 tableView.deselectRow(at: indexPath, animated: true) }
特殊场景拓展(仅多数据源混合等特殊情况需要)
如果你的业务确实需要将标识符直接绑定到Cell实例上,可以自定义Cell类添加专属属性,在cellForRowAt赋值:
// 自定义Cell类 class CustomTableViewCell: UITableViewCell { // 新增存储标识符的属性 var customIdentifier: String? } // cellForRowAt中赋值 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomTableViewCell cell.customIdentifier = cellIdentifierList[indexPath.row] // 其他Cell配置逻辑 return cell } // 此时didSelectRowAt也可以从Cell中取值,不推荐普通场景使用 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if let cell = tableView.cellForRow(at: indexPath) as? CustomTableViewCell, let selectId = cell.customIdentifier { self.cellPressedId = selectId } tableView.deselectRow(at: indexPath, animated: true) }
内容的提问来源于stack exchange,提问作者JoSO86
相关产品推荐
相关产品推荐

