You need to enable JavaScript to run this app. iOS开发:tableView左滑删cell时Firestore购物车全量删除问题求助
优惠活动
大模型
产品
解决方案
定价
更多

iOS开发:tableView左滑删cell时Firestore购物车全量删除问题求助

问题原因与修复方案
  • 核心问题1:现有Cart模型未存储Firestore对应购物车商品的文档ID,删除时无法定位到指定条目
  • 核心问题2:左滑删除逻辑存在错误,大概率直接删除了整个CartItems集合而非单个文档
  • 优化点1:getCartProducts拉取数据前未清空本地数组,会导致多次进入页面数据重复累加
  • 优化点2:总价计算逻辑放在numberOfRowsInSection中不合理,该方法会频繁触发,影响性能

修复步骤

1. 修改Cart结构体,新增文档ID字段

struct Cart
{
    var documentID: String // 新增字段,存储Firestore对应文档ID
    var photoKeyCart: String
    var foodCart: String
    var priceCart: Int
}

2. 修正数据拉取方法

func getCartProducts() {
        let db = Firestore.firestore()
        guard let userID = Auth.auth().currentUser?.uid else { return }
        // 拉取前先清空本地旧数据,避免重复累加
        self.cart.removeAll()
        db.collection("CartDatabase").document(userID).collection("CartItems").getDocuments {  (document, error) in
            if let error = error {
                print(error)
                return
            } 
            guard let documents = document?.documents else { return }
            for document in documents {
                let data = document.data()
                guard let photoKey = data["photoKeyCart"] as? String,
                      let foodName = data["foodCart"] as? String,
                      let price = data["priceCart"] as? Int else { continue }
                // 把文档ID存入模型
                let newEntry = Cart(
                    documentID: document.documentID,
                    photoKeyCart: photoKey, 
                    foodCart: foodName, 
                    priceCart: price
                )
                self.cart.append(newEntry)
            }
            DispatchQueue.main.async {
                self.cartTableView.reloadData()
                // 数据更新后单独计算总价
                self.calculateTotalPrice()
            }
        }
    }

3. 新增单独的总价计算方法

func calculateTotalPrice() {
    let sum = cart.reduce(0, { $0 + $1.priceCart })
    priceTotalLabel.text = "\(sum) lei"
}

// 修正后的行数返回逻辑,移除原有总价计算代码
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return cart.count
}

4. 实现正确的左滑删除逻辑

func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
    let deleteAction = UIContextualAction(style: .destructive, title: "删除") { [weak self] (_, _, completion) in
        guard let self = self else { return }
        let targetItem = self.cart[indexPath.row]
        let db = Firestore.firestore()
        guard let userID = Auth.auth().currentUser?.uid else { return }
        // 仅删除指定ID对应的单个文档,不要操作整个集合
        db.collection("CartDatabase").document(userID).collection("CartItems").document(targetItem.documentID).delete { error in
            if let error = error {
                print("删除失败:\(error)")
                completion(false)
                return
            }
            // 删除成功后同步更新本地数组与UI
            DispatchQueue.main.async {
                self.cart.remove(at: indexPath.row)
                self.cartTableView.deleteRows(at: [indexPath], with: .automatic)
                self.calculateTotalPrice()
                completion(true)
            }
        }
    }
    return UISwipeActionsConfiguration(actions: [deleteAction])
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 04:27:04