You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift大学项目中TableView单元格重复显示问题求助

问题分析与解决办法

嘿,这问题很典型,我一眼就瞅出根源啦!

你当前的代码里犯了个容易踩的小错误:

  • numberOfSections 方法返回了 tableData.count,等于创建了10个分组(section)
  • 同时每个分组的行数 numberOfRowsInSection 又返回了 tableData.count,等于每个分组都显示10行

这就相当于搞了10个分组,每个分组都把整个数组内容重复展示一遍,最终自然会出现10×10=100条重复内容!

修正后的代码

// TableData是存储单元格数据的数组
override func numberOfSections(in tableView: UITableView) -> Int {
    // 只需要一个分组就够了
    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // 分组行数等于数组元素数量
    return tableData.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "locationCell", for: indexPath)
    let mapLocation = tableData[indexPath.row]
    cell.textLabel?.text = mapLocation.name
    return cell
}

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    selectedLocation = tableData[indexPath.row]
    performSegue(withIdentifier: "fromTableToMap", sender: selectedLocation)
}

补充说明

如果你的需求本来就是要多分组,那得重新设计数据结构(比如用二维数组,每个section对应一个子数组),但从你描述的“本应显示10个单元格”来看,显然不需要多分组,把numberOfSections改成返回1就完美解决问题啦!

内容的提问来源于stack exchange,提问作者vickylaram

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:37:49