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
相关产品推荐
相关产品推荐

