Swift中TableView分组展示食物数据出现条目重复问题求助
问题根源
你的代码存在4处核心逻辑错误,直接导致条目重复、分组逻辑失效:
- 数据源未按食物类别分组:当前使用平铺的
Food数组直接适配分组TableView,结构完全不匹配 numberOfSections返回值错误:当前返回所有食物的总数量,导致每个食物单独占用一个section,而非每个食物类别占用一个sectionnumberOfRowsInSection返回值完全错误:当前返回的是对应section下食物名称的字符串长度,比如食物名叫"意式披萨"就会返回4,导致同一个section下生成4行相同内容cellForRowAt取值逻辑错误:仅通过indexPath.section取食物对象,完全未用到indexPath.row,导致同一个section下所有行的内容完全一致
修复方案
第一步:改造数据源结构
将从Firestore拉取到的平铺Food数组,按typeFood字段分组为适配分组TableView的结构:
// 定义分组后的数据源:外层数组每个元素对应一个食物分类,存储分类名和该分类下的所有食物数组 var groupedFood: [(typeName: String, foodList: [Food])] = [] // 拉取到原始food数组后,执行分组逻辑,完成后刷新TableView func groupFoodAfterFetch() { // 按食物类别分组为字典 let tempGroupDict = Dictionary(grouping: food) { $0.typeFood } // 转为有序数组,可根据需求调整分类的排序规则 groupedFood = tempGroupDict.sorted { $0.key < $1.key }.map { (typeName: $0.key, foodList: $0.value) } tableView.reloadData() }
第二步:修改TableView代理方法
将原代理方法的取值逻辑替换为适配分组数据源的逻辑:
// 返回分类的总数量作为section数 func numberOfSections(in tableView: UITableView) -> Int { return groupedFood.count } // 返回对应分类下的食物数量作为该section的行数 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return groupedFood[section].foodList.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "FoodTableViewCell", for: indexPath) as! FoodTableViewCell // 先取对应分类,再按行号取该分类下对应的食物对象 let mancare = groupedFood[indexPath.section].foodList[indexPath.row] // 原有cell属性赋值逻辑保持不变即可 let storageRef = Storage.storage().reference() let photoRef = storageRef.child(mancare.photoKeyRestaurant) cell.foodImage.sd_setImage(with: photoRef) cell.descriptionLabel.text = mancare.foodDescription cell.foodNameLabel.text = mancare.foodName cell.priceLabel.text = "\(mancare.priceFood) lei" cell.foodImage.layer.borderWidth = 1 cell.foodImage.layer.masksToBounds = false cell.foodImage.layer.borderColor = UIColor.black.cgColor cell.foodImage.layer.cornerRadius = cell.foodImage.frame.height/2 cell.foodImage.clipsToBounds = true return cell } // section标题取对应分类的名称 func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return groupedFood[section].typeName }
内容的提问来源于stack exchange,提问作者Vasile
相关产品推荐
相关产品推荐

