【问题标题】:How to add data into Firestore Swift by tapping on a cell如何通过点击单元格将数据添加到 Firestore Swift
【发布时间】:2023-03-25 08:21:01
【问题描述】:

我有更多的餐馆,每家都有不同的食物。Look here 这就是我从 Firestore 中检索数据的方式。在前面的控制器中,我有一个餐馆列表,每个都包含一个食物列表。

struct Food {
    
    var photoKeyRestaurant: String
    var foodName: String
    var foodDescription: String
    var restaurantName: String
    var priceFood: Int
    
}

class RestaurantViewController: UIViewController {
    
   
    var restaurantName: String!
    var food: [Food] = []
  
    
    
    private let tableView: UITableView = {
        let table = UITableView()

        return table
    }()

func getDatabaseRecords() {
        
       
            
            let db = Firestore.firestore()
           //  Empty the array
          food = []
            
        db.collection("RestaurantViewController").whereField("restaurantName", isEqualTo: restaurantName).getDocuments { (snapshot, error) in
                if let error = error {
                    print(error)
                    return
                } else {
                    for document in snapshot!.documents {
                        let data = document.data()
                        let newEntry = Food(photoKeyRestaurant: data["photoKeyRestaurant"] as! String, foodName: data["foodName"] as! String, foodDescription: data["foodDescription"] as! String, restaurantName: data["restaurantName"] as! String , priceFood: data["priceLabel"] as! Int
                        )
                        
                            
                            
                            
                        self.food.append(newEntry)
                    }
                }
                DispatchQueue.main.async {
                 //  self.datas = self.filteredData
                   self.tableView.reloadData()
                }
            }
        }

如何通过在此功能中按 + 到 Firestore 来添加所选单元格的数据? 我在我的 FoodTableViewCell 中创建了一个协议,并在 RestaurantViewController 中调用了它。

 func diddTapButtonCell(_ cell: FoodTableViewCell) {
    
        let db = Firestore.firestore()
        db.collection("cart").addDocument.(data: foodName) { (err) in
            
        } 

已编辑:添加表格视图

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return food.count
      
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "FoodTableViewCell", for: indexPath) as! FoodTableViewCell
        cell.delegate = self
        let mancare = food[indexPath.row]
        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"
        //Fac ca imaginea sa fie cerc  - start
        
        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
     
        //Fac ca imaginea sa fie cerc  - finish
        return cell
    }
    

这是我的表格视图单元格代码


protocol CustomCellDelegate {
    func diddTapButtonCell (_ cell: FoodTableViewCell)
}
class FoodTableViewCell: UITableViewCell {
    
    var delegate: CustomCellDelegate?
   
    @IBOutlet weak var foodImage: UIImageView!
    
    @IBOutlet weak var foodNameLabel: UILabel!
    
    @IBOutlet weak var descriptionLabel: UILabel!
    
    @IBOutlet weak var priceLabel: UILabel!
    
    override func awakeFromNib() {
        super.awakeFromNib()
        
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        
    }
    
    
    
    @IBAction func addToCart(_ sender: Any) {
        delegate?.diddTapButtonCell(self)
    }
    
    
    
}

【问题讨论】:

  • 请使用您的 UITableView 的代码编辑您的问题。
  • @Todd 看看
  • 当您按下 + 按钮时是否将 diddTapButtonCell 添加为目标?如果通过情节提要/界面构建器连接,我看不到“objc”或“IBAction”。此外,如果您能够按单元格上的任何位置,我将改为在 cellForRowAt 下实现 didSelectRowAt UITableViewDelegate 方法
  • @landnbloc 我编辑了这个问题。查看 TableView 单元格
  • 把 didTapButtonCell 变成一个闭包 "var didTapButton : (()->())?"然后在你的tableview的cellForAt函数中给它一个值“cell.didTapButton = { //直接从这里处理单元格操作}并确保将didTapButton?()添加到addToCart。这应该可以工作

标签: swift firebase uitableview google-cloud-firestore


【解决方案1】:

https://firebase.google.com/docs/firestore/manage-data/add-data
这是我的一个项目中的一个示例,用于将数据添加到 Firestore。

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

【讨论】:

  • 感谢您与我分享这些,在 newValueDict 中,如何从当前单元格传递我的值?
  • 您实际上不想从单元格中传递数据,因为单元格被重复使用,因此在表格视图滚动时获得正确的数据并不可靠。这就是为什么“cell.didTapButton = { self?.updateDocument(newDataDict: ["foodDesc": mancare.foodDescription]) }” 是个好主意的原因。这样您就可以直接从数据源添加数据
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多