首页 > 解决方案 > 如何使用 Action 存储来自特定单元格的数据?

问题描述

我有ViewController一个TableView里面。我也有一个TableViewCell控制器。

我表格的每个单元格都有来自 Firebase 的信息和一个按钮。

这里的目标是在我单击按钮时将我的单元格的信息添加到我的数据库中。

基本上,我有一个歌曲列表,add button每首歌曲都有一个,当我点击 时,我想在我的用户帐户中添加一首歌曲add

歌曲列表显示得很好,但是当我单击“添加”按钮时,我不知道如何将这首歌的信息放入我的数据库中。

型号代码:

import Foundation

class ServiceModel {

    var name: String?
    var category: String?
    var pricing: String?

    init(name: String?, category: String?, pricing: String?){
        self.name = name
        self.category = category
        self.pricing = pricing
    }
}

TableViewCell 代码:

class PopularTableViewCell: UITableViewCell {

    @IBOutlet weak var imageService: UIImageView!
    @IBOutlet weak var labelName: UILabel!
    @IBOutlet weak var labelCategory: UILabel!
    @IBOutlet weak var labelPricing: UILabel!

视图控制器代码:

import UIKit
import FirebaseDatabase
import FirebaseAuth

class AddSubViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {

    var refServices:DatabaseReference!

    @IBOutlet weak var ListPop: UITableView!

    var serviceList = [ServiceModel]()

    var databaseHandle:DatabaseHandle?

    let userID = Auth.auth().currentUser?.uid


    @IBAction func addSub(_ sender: Any) {

        let ref = Database.database().reference()
            let usersReference = ref.child("users")
            let uid = Auth.auth().currentUser?.uid
            let thisUserReference = usersReference.child(uid!).child("subs").childByAutoId()
        thisUserReference.setValue("test")

**// I want to put the pricing value of the song of my cell instead of "test" in: setValue("test")**

    }

    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return serviceList.count
    }

    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "PopCell", for: indexPath) as! PopularTableViewCell

        let service: ServiceModel

        service = serviceList[indexPath.row]

        cell.imageService?.image = UIImage(named: service.name! + ".png")
        cell.labelName?.text = service.name
        cell.labelCategory?.text = service.category
        cell.labelPricing?.text = service.pricing

        return cell
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        ListPop.delegate = self
        ListPop.dataSource = self

        refServices = Database.database().reference().child("Categories")

        refServices.observe(DataEventType.value, with: { (snapshot) in

            if snapshot.childrenCount > 0 {

                self.serviceList.removeAll()

                for services in snapshot.children.allObjects as! [DataSnapshot] {
                    let serviceObject = services.value as? [String: AnyObject]
                    let serviceName  = serviceObject?["Name"]
                    let serviceCategory  = serviceObject?["Category"]
                    let servicePricing = serviceObject?["Pricing"] as! String + " €"
                    let service = ServiceModel(name: serviceName as! String?, category: serviceCategory as! String?, pricing: servicePricing as String?)

                    self.serviceList.append(service)
                }

                self.ListPop.reloadData()
            }
        })
    }

}

我想将我的手机歌曲的定价值而不是“测试”放在:setValue("test")

标签: swiftfirebaseuitableview

解决方案


如果每个单元格都有按钮,您可以在用户按下按钮后简单地保存模型,因为您有自定义模型(可能只是 struct btw),您可以为它和表格视图的cellForRowAt数据源方法中的每个单元格创建变量,您可以分配它

class PopularTableViewCell: UITableViewCell {

    var service: ServiceModel!

    @IBAction func addButtonPressed(_ sender: UIButton) {
        ... // save certain service
    }

}

...

public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "PopCell", for: indexPath) as! PopularTableViewCell

    let service = serviceList[indexPath.row]

    cell.service = service // <---

    cell.imageService?.image = UIImage(named: service.name! + ".png")
    cell.labelName?.text = service.name
    cell.labelCategory?.text = service.category
    cell.labelPricing?.text = service.pricing

    return cell
}

推荐阅读