如何从tableview中删除一个单元格

How do I delete a cell from tableview

我正在尝试从表视图和 Firestore 中删除一个单元格。 这是我声明购物车的方式:

struct Cart
{
    var photoKeyCart: String
    var foodCart: String
    var priceCart: Int
}

var cart: [Cart] = [] // This is in the cart controller

这是我的表格视图,其中有我的购物车商品:

extension CartViewController: UITableViewDelegate, UITableViewDataSource
{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        var sum = 0
        
        for item in cart{
            sum += item.priceCart
        }
        
        priceTotalLabel.text = "\(sum) lei"
        return cart.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = cartTableView.dequeueReusableCell(withIdentifier: "CartTableViewCell", for: indexPath) as! CartTableViewCell
        let carts = cart[indexPath.row]
        let storageRef = Storage.storage().reference()
        let photoRef = storageRef.child(carts.photoKeyCart)
        
        cell.foodInCartPrice.text = " \(carts.priceCart) lei "
        cell.foodInCartName.text = carts.foodCart
        cell.foodInCartImage.sd_setImage(with: photoRef)
        cell.foodInCartImage.layer.borderWidth = 1
        cell.foodInCartImage.layer.masksToBounds = false
        cell.foodInCartImage.layer.borderColor = UIColor.black.cgColor
        cell.foodInCartImage.layer.cornerRadius = cell.foodInCartImage.frame.height/2
        cell.foodInCartImage.clipsToBounds = true
        
        return cell
        
    }

这就是我将数据从 Firestore 获取到购物车的方式。这在加载的视图中调用。

func getCartProducts() {
        
        let db = Firestore.firestore()
        let userID = (Auth.auth().currentUser?.uid)!
        db.collection("CartDatabase").document(userID).collection("CartItems").getDocuments {  (document, error) in
            if let error = error {
                print(error)
                return
            } else {
                for document in document!.documents {
                    let data = document.data()
                    let newEntry = Cart(photoKeyCart: data["photoKeyCart"] as! String, foodCart: data["foodCart"] as! String , priceCart: data["priceCart"] as! Int
                    )
                    
                    
                    
                    
                    self.cart.append(newEntry)
                }
            }
            DispatchQueue.main.async {
                //  self.datas = self.filteredData
                self.cartTableView.reloadData()
            }
        }
    }

而且,这就是我尝试从表视图以及 Firestore 中删除单元格的方式。

func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }
    
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        
        
        let carts = cart[indexPath.row]
        let storageRef = Storage.storage().reference()
        let photoRef = storageRef.child(carts.photoKeyCart)
        
        photoRef.delete { error in
            if let error = error {
                print(error.localizedDescription)
            } else {
                print("File deleted successfully")
            }
        }
        
        
        
     
        let db = Firestore.firestore()
        let userID = (Auth.auth().currentUser?.uid)!
        db.collection("CartDatabase").document(userID).collection("CartItems").getDocuments {  (document, error) in
            if let error = error {
                print(error.localizedDescription)
            } else {
                for document in document!.documents {
                    //print("\(document.documentID) => \(document.data())")
                    db.collection("CartDatabase").document(userID).collection("CartItems").document(document.documentID).delete()
                    //self.db.collection("users").document((user?.uid)!).collection("children").document("\(document.documentID)").delete()
                }
            }}
        
        
        
      
        cart.remove(at: indexPath.row)
        tableView.deleteRows(at: [indexPath], with: .fade)
        
    }
}

我有以下问题。当我尝试删除单元格时,它起作用了,但是当我关闭购物车并再次返回购物车时,它会删除购物车中的所有商品,而不仅仅是我试图删除的商品。

我想要实现的目标:只删除选中的单元格。 帮助:D

更新: 我有一个包含食物的表格视图,每个单元格都是不同的食物之王。我有一个加号按钮,当点击加号按钮时,我会将食物的数据发送到 Firestore,然后在购物车中检索数据。

这就是我将数据发送到购物车的方式:

    func updateDocument(collection: String, newValueDict: [String : Any], completion:@escaping (Bool) -> Void = {_ in }) {
        
                    
                     let db = Firestore.firestore()
        let userID = (Auth.auth().currentUser?.uid)!
        db.collection(collection).document(userID).collection("CartItems").document().setData(newValueDict, merge: true){ err in
                        if let err = err {
                            print("Error writing document: \(err)")
                            completion(false)
                            
                        }else{
                            
                            completion(true)
                          
                           
                        }
                    }
                     
                 }

当我点击单元格时:

cell.didTapButton = {
            
            self.updateDocument(collection: "CartDatabase",newValueDict: ["foodCart" : mancare.foodName, "photoKeyCart": mancare.photoKeyRestaurant, "priceCart": mancare.priceFood])
           
        }

查看照片 Photo1 Photo2

在没有看到所有代码的情况下,很难提供一个具体的例子,但让我在较高的层次上介绍一下。

假设我们有一个 posts class 对象

class PostsClass {
   var docId = ""
   var post = ""
}

和一个 class 数组(又名 'dataSource')将它们存储在

var postsArray = [PostsClass]()

第一步是从 Firebase 加载所有 post,在每个 class 中存储 docId 和 post 文本,然后将 class 存储在数据源数组。

myFirebase.getDocuments { doc...
   for doc in documents { //iterate over the documents and populate the array
      let post = PostClass(populate with data from firebase)
      self.postsArray.add(post)
   }
}

dataSouce 数组将如下所示

postsArray[0] = some post
postsArray[1] = another post

等,所有这些都显示在 tableView 中。

然后用户决定删除第 1 行的 post。因此他们滑动第一行,这会触发 tableView 委托事件,让应用知道滑动行的索引。

第 1 步:然后根据滑动的行索引

从数组中获取 post
let postToDelete = self.postsArray[swiped index]
let docIdToDelete = postsToDelete.docID

第 2 步:然后从数组中删除它

self.postsArray.deleteRow(atIndex: swiped index)

第 3 步:然后将其从 Firebase 中删除。

self.my_firebase.collection("posts").document(docIdToDelete).delete {....

请注意,func tableView:tableView:commit editingStyle 将在删除行时呈现 .delete 的编辑样式,并在 indexPath.row

中提供索引