UITableView插入行后如何让右上角Label正确显示图片分数汇总?
问题分析与解决方案
嘿,我看到你的问题了——插入新行后图片显示正常,但右上角的分数统计Label总是不对对吧?咱们来一步步拆解问题,然后修复它:
核心问题出在哪?
cellForRowAt里维护计数数组是错误的:UITableView的cell是会被复用的,每次cell滚动出屏幕再回来、或者插入新行触发刷新时,cellForRowAt都会被调用。你在这个方法里往pic1/pic2/pic3数组里加元素,会导致同一个行被重复计数,统计数据自然就乱了。- 插入行的IndexPath错误:你用了
IndexPath(row: -1 , section: 0),但row的索引是从0开始的,不存在-1这个位置,应该用row:0才对,因为你是在imgName的第0位插入元素。
修复后的完整代码
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var lblRowStatus: UILabel! @IBOutlet weak var tblList:UITableView! var imgName = [String]() override func viewDidLoad() { super.viewDidLoad() tblList.tableFooterView = UIView.init(frame: .zero) tblList.dataSource = self tblList.delegate = self } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return imgName.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for : indexPath) let pathRow = indexPath.row + 1 // 只负责显示图片,不再维护计数数组 if pathRow % 7 == 0{ cell.imageView?.image = UIImage(named: "pic3") }else if pathRow % 3 == 0{ cell.imageView?.image = UIImage(named: "pic2") }else { cell.imageView?.image = UIImage(named: "pic1") } return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 30.0 } @IBAction func addRow(_ sender: UIButton) { tblList.beginUpdates() imgName.insert("New Element", at: 0) // 修正IndexPath的row为0 tblList.insertRows(at: [IndexPath(row: 0 , section: 0)], with: .automatic) tblList.endUpdates() // 重新计算各类图片的数量和总分 let totalRows = imgName.count // 计算pic3的数量:能被7整除的行数 let pic3Count = totalRows / 7 // 计算pic2的数量:能被3整除但不能被7整除的行数(减去同时被7和3整除的,避免重复统计) let pic2Count = (totalRows / 3) - (totalRows / 21) // pic1的数量是总行数减去前两者 let pic1Count = totalRows - pic2Count - pic3Count // 计算总分:pic1(4分)、pic2(2分)、pic3(1分) let totalScore = pic1Count * 4 + pic2Count * 2 + pic3Count * 1 // 更新Label内容,同时显示数量和总分 lblRowStatus.text = """ pic1: \(pic1Count) pic2: \(pic2Count) pic3: \(pic3Count) 总分: \(totalScore) """ print(imgName.count) } }
关键优化点解释
- 移除计数数组:不再用
pic1/pic2/pic3数组来统计,而是每次添加行后,通过数学计算直接得到各类图片的数量——这样既避免了复用cell导致的重复计数,也更高效。 - 修正插入行的IndexPath:把
row:-1改成row:0,和imgName.insert的位置对应,确保新行能正确插入。 - 新增总分计算:按照你给出的分值(pic1=4、pic2=2、pic3=1)直接计算总分,更新到Label里。
这样修改后,不管你插入多少行,或者滚动TableView,Label的统计数据都会保持准确啦!
内容的提问来源于stack exchange,提问作者CagkanT.
相关产品推荐
相关产品推荐

