Swift 4中Table View数组数据重复显示问题及数据展示需求
解决Swift 4中TableView/CollectionView数组数据重复显示的问题
嘿,我之前也碰到过一模一样的TableView重复显示数据的坑,大概率是数据源处理或者cell复用机制没做对,咱们一步步排查解决!
最常见的原因:Cell复用未重置内容
TableView的cell是复用机制设计的,如果配置cell时只设置新数据、没清空之前的内容,就会导致旧数据残留,看起来像是重复显示。比如之前的cell显示了"2000.0",复用的时候新数据没覆盖,就会重复出现。
解决办法1:配置cell时先重置内容
在cellForRowAt方法里,先把所有UI元素的内容清空,再设置当前行的数据:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "YourCellID", for: indexPath) as! YourCustomCell // 先重置所有UI元素,避免复用残留 cell.inrLabel.text = "" cell.timeLabel.text = "" // 再设置当前行的对应数据 let amount = inr[indexPath.row] let time = reqtime[indexPath.row] cell.inrLabel.text = amount cell.timeLabel.text = time return cell }
解决办法2:利用prepareForReuse方法自动重置
在自定义cell类里重写prepareForReuse方法,让cell被复用前自动清空内容:
class YourCustomCell: UITableViewCell { @IBOutlet weak var inrLabel: UILabel! @IBOutlet weak var timeLabel: UILabel! override func prepareForReuse() { super.prepareForReuse() // 重置所有需要复用的UI元素 inrLabel.text = "" timeLabel.text = "" } }
第二个可能:数据源数组被重复追加
如果你是从网络请求或者本地加载数据,每次都把新数据追加到原数组里,而不是替换原数组,就会导致数组里的内容重复,TableView自然会显示重复行。
错误示例(会导致重复):
// 每次请求成功后都追加,数组内容越来越多 inr += newInrData reqtime += newReqtimeData
正确做法:替换数组,再刷新TableView
// 直接用新数据替换原数组,避免重复 inr = newInrData reqtime = newReqtimeData // 记得刷新TableView,让新数据生效 tableView.reloadData()
第三个检查点:确保两个数组长度一致
你的reqtime数组看起来被截断了(最后是"20..."),要保证inr和reqtime的元素数量完全一致!如果一个长一个短,要么会崩溃,要么会出现数据错位/重复的情况。
可以先打印两个数组的长度确认:
print("inr数组长度:\(inr.count)") print("reqtime数组长度:\(reqtime.count)")
如果长度不一致,赶紧修正数据源,保证每个位置的金额和时间一一对应。
优化建议:用模型类管理数据
把分散的两个数组封装成一个模型类,不仅能避免数组长度不一致的问题,代码也更清晰易维护:
// 定义交易模型 struct Transaction { let amount: String let time: String } // 把原来的两个数组转换成模型数组 let transactions: [Transaction] = [ Transaction(amount: "200.0", time: "2018-04-11 13:54:46"), Transaction(amount: "1200.0", time: "2018-04-09 16:31:42"), Transaction(amount: "500.0", time: "2018-04-09 12:26:32"), // ... 其他所有数据 ]
之后在TableView里直接用模型数组:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return transactions.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "YourCellID", for: indexPath) as! YourCustomCell let transaction = transactions[indexPath.row] cell.inrLabel.text = transaction.amount cell.timeLabel.text = transaction.time return cell }
内容的提问来源于stack exchange,提问作者user9368327
相关产品推荐
相关产品推荐

