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

Swift中TableView分组展示食物数据出现条目重复问题求助

问题根源

你的代码存在4处核心逻辑错误,直接导致条目重复、分组逻辑失效:

  • 数据源未按食物类别分组:当前使用平铺的Food数组直接适配分组TableView,结构完全不匹配
  • numberOfSections返回值错误:当前返回所有食物的总数量,导致每个食物单独占用一个section,而非每个食物类别占用一个section
  • numberOfRowsInSection返回值完全错误:当前返回的是对应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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 06:54:04