Swift 4(XCode 9)UITableView选中单元格文本值存入数组问题
解决TableView选中单元格存值错误的问题
嘿,我来帮你搞定这个Xcode 9 Swift 4里的TableView问题!你遇到的核心问题是cell复用机制导致的——直接在setSelected里存值会因为cell被复用时重复触发,进而把错误的文本塞进数组,滚动时这个问题会更明显。下面给你一套靠谱的解决方案:
1. 把选中逻辑移到ViewController的代理方法里
不要在cell内部处理存值,转而用TableView的didSelectRowAt和didDeselectRowAt代理方法,这两个方法直接对应行的indexPath,完全不受cell复用影响。
示例代码:
// 假设你的数据源数组(存所有食物名称) var foodsArray: [String] = ["苹果", "香蕉", "汉堡"] var foodDetailInfoArray: [String] = [] // 选中行时的处理 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let selectedFood = foodsArray[indexPath.row] // 避免重复添加(如果需要允许多选重复可去掉此判断) if !foodDetailInfoArray.contains(selectedFood) { foodDetailInfoArray.append(selectedFood) print("已添加:\(selectedFood)") } // 更新当前cell的选中UI if let cell = tableView.cellForRow(at: indexPath) as? YourCustomCell { cell.isSelected = true } } // 取消选中行时的处理(支持取消选中的话需要) func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) { let deselectedFood = foodsArray[indexPath.row] // 从数组中移除取消选中的项 if let removeIndex = foodDetailInfoArray.firstIndex(of: deselectedFood) { foodDetailInfoArray.remove(at: removeIndex) print("已移除:\(deselectedFood)") } // 恢复当前cell的UI if let cell = tableView.cellForRow(at: indexPath) as? YourCustomCell { cell.isSelected = false } }
2. 让cell只负责UI更新
修改cell的setSelected方法,只处理选中时的样式变化,别碰存值逻辑:
class YourCustomCell: UITableViewCell { @IBOutlet weak var foodName: UILabel! override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // 这里只写UI相关代码,比如背景色、文字颜色 self.backgroundColor = selected ? .lightGray : .white self.foodName.textColor = selected ? .white : .black } }
3. 修复滚动时的选中状态丢失问题
在cellForRowAt方法里,根据foodDetailInfoArray的内容设置cell的选中状态,这样滚动时复用的cell能正确显示是否被选中:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "YourCellID", for: indexPath) as! YourCustomCell let food = foodsArray[indexPath.row] cell.foodName.text = food // 根据数组判断当前cell是否应该处于选中状态 cell.isSelected = foodDetailInfoArray.contains(food) return cell }
这样调整后,不管怎么滚动表格,选中的文本都会准确存入foodDetailInfoArray,不会出现错误存值的情况啦!
内容的提问来源于stack exchange,提问作者kavyajha1004
相关产品推荐
相关产品推荐

