如何将数据从TableViewCell中的按钮传递到View Controller? [英] How pass data from button in TableViewCell to View Controller?

查看:59
本文介绍了如何将数据从TableViewCell中的按钮传递到View Controller?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个ViewController,其中一个叫做ProductListVC,另一个叫MoreInfoVC.我在ProductListViewController上有一个tableView,它向单元格显示多个标签和按钮.

I have 2 ViewControllers, one of is called ProductListVC the other is MoreInfoVC. I have a tableView on ProductListViewController that shows cells multiple labels and buttons.

MoreInfoVC是一个Modal弹出式VC,其中带有一些商标,名称和说明标签.我已将所有数据存储在Firestore中,并且已经创建了class(ProductList)来帮助检索从Cloud Firestore在表视图中显示数据的数据.

MoreInfoVC is a Modal pop-up VC with a few labels for the brand, Name, and description. I have all my data stored in Firestore and already have created class(ProductList) to help retrieve the data which presents the data in the tableview from the Cloud Firestore.

我需要做的是使用单个TBV单元中的MoreInfo按钮将数据传递到MoreInfoVC,以便它可以显示所选产品的信息

what I need to do is use the MoreInfo button in the individual TBV cell to pass the data into MoreInfoVC so that it can present the information of selected product

现在,我可以使用didSelectRowAt方法或在prepare segue方法中使用indexPathForSelectedRow轻松地做到这一点.但是这两种情况都要求我点击单元格本身而不是按钮.

Now i can easily do this with either didSelectRowAt method or using indexPathForSelectedRow in prepare segue method. But both cases requires me to tap on the cell itself but not the button.

我如何能够通过更多信息"按钮将来自单个表单元格的数据传递到更多信息VC"上.我认为我走了正确的路,因为似乎我的MoreInfoVC正在传递数据,但此刻正在显示此信息

how would I be able to pass data from an individual tableview cell through the MoreInfo button onto the MoreInfoVC. I think I'm on the right path since it seems my MoreInfoVC is passing data but showing this at the moment

    import UIKit
    import Firebase
    import FirebaseFirestore

    class ProductListVC: UIViewController {

        @IBOutlet weak var productListTableView: UITableView!

        var productInventory: [ProductList] = []
        var productSetup: [ProductList] = []

        override func viewWillAppear(_ animated: Bool) {
            super.viewWillAppear(animated)
        }

        override func viewDidLoad() {
            super.viewDidLoad()

            productListTableView.dataSource = self
            productListTableView.delegate = self
            searchBar.delegate = self

            fetchProducts { (products) in
                self.productSetup = products
                self.productListTableView.reloadData()
            }

        }
       func fetchProducts(_ completion: @escaping ([ProductList]) -> Void) {
           let ref = Firestore.firestore().collection("products")
      ref.addSnapshotListener { (snapshot, error) in
                guard error == nil, let snapshot = snapshot, !snapshot.isEmpty else {
                    return
                }
                completion(snapshot.documents.compactMap( {ProductList(dictionary: $0.data())} ))
            }
        }
    }

    extension ProductListVC: UITableViewDelegate, UITableViewDataSource {
        func numberOfSections(in tableView: UITableView) -> Int {
            return 1
        }
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

            return productSetup.count
        }

        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            guard let cell = tableView.dequeueReusableCell(withIdentifier: "ProductListCell") as?
    ProductListCell else { return UITableViewCell() }

             cell.configure(withProduct: productSetup[indexPath.row])

             cell.delegate = self

          return cell
      }

  }

  extension ProductListVC: ProductListCellDelegate {
      func onTouchInfoButton(from cell: ProductListCell) {
          self.selectedProduct = cell.product
      }

      override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
          self.performSegue(withIdentifier: "MoreInfo", sender: self)
      }
 }


   import UIKit
   import Firebase

   class MoreInfoVC: UIViewController {

        var products: ProductList?

        @IBOutlet weak var productName: UILabel!

        override func viewDidLoad() {
             super.viewDidLoad()

           // Do any additional setup after loading the view.

           productName.text = "\(String(describing: products?.brand)): \(String(describing: products?.name))"
       }

       @IBAction func closeBtn(_ sender: Any) {
            dismiss(animated: true, completion: nil)
            print("Close More Information")
       }
   }


  import UIKit
  import SDWebImage
  import Firebase

  protocol ProductListCellDelegate: class {
      func onTouchInfoButton(from cell: ProductListCell)
  }

  class ProductListCell: UITableViewCell {

      weak var product: ProductList!
      weak var delegate: ProductListCellDelegate?

      @IBOutlet weak var productImage: UIImageView!
      @IBOutlet weak var productName: UILabel!
      @IBOutlet weak var categoryLabel: UILabel!
      @IBOutlet weak var strain: UILabel!

      @IBOutlet weak var moreInfo: RoundButton!

      func configure(withProduct product: ProductList) {
          productName.text = "\(String(describing: product.brand)): \(String(describing: product.name))"
          categoryLabel.text = product.category
          productImage.sd_setImage(with: URL(string: product.imageUrl))
          strain.text = product.strain

          self.product = product
      }

      @IBAction func infoButtonAction(_ sender: Any) {
          self.delegate?.onTouchInfoButton(from: self)
      }
  }

推荐答案

函数 @IBAction func infoButtonAction(_ sender:Any){} 应该在 ProductListCell

点击该按钮时,通过 delegate closure ProductListVC 连接以获取所选产品.

When that button is tapped, connect with the ProductListVC by delegate or closure to get the selected product.

更新

使用代表:更新您的 ProductListCell

import UIKit
import SDWebImage
import Firebase

protocol ProductListCellDelegate: class {
    func onTouchInfoButton(from cell: ProductListCell)
}

class ProductListCell: UITableViewCell {

      @IBOutlet weak var productImage: UIImageView!
      @IBOutlet weak var dispensaryName: UILabel!
      @IBOutlet weak var productName: UILabel!
      @IBOutlet weak var thcPercent: UILabel!
      @IBOutlet weak var cbdPercent: UILabel!
      @IBOutlet weak var categoryLabel: UILabel!
      @IBOutlet weak var categoryStrain: UILabel!

      @IBOutlet weak var moreInfo: RoundButton!
      weak var product: Product!
      weak var delegate: ProductListCellDelegate?

      func configure(withProduct product: ProductList) {
          self.product = product
          productName.text = "\(String(describing: product.brand)): \(String(describing: product.name))"
          dispensaryName.text = product.dispensaryName
          categoryLabel.text = product.category
          productImage.sd_setImage(with: URL(string: product.imageUrl))
          cbdPercent.text = product.cbd
          thcPercent.text = product.thc
          categoryStrain.text = product.strain
      }

      @IBAction func infoButtonAction(_ sender: Any) {
          self.delegate?.onTouchInfoButton(from: self)
      }
}

在您的 ProductListVC 中:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            guard let cell = tableView.dequeueReusableCell(withIdentifier: "ProductListCell") as?
    ProductListCell else { return UITableViewCell() }

    cell.configure(withProduct: productSetup[indexPath.row])

    cell.delegate = self

    return cell
}

extension ProductListVC: ProductListCellDelegate {
     func onTouchInfoButton(from cell: ProductListCell) {
        let selectedProduct = cell.product
        // Do your stuff here 
     }
}

更新

因为您使用segue进行导航,所以我们创建一个变量以将所选产品存储在ProductListVC中

Because you use segue for navigation so let's create a variable to store your selected product in your ProductListVC

import UIKit
    import Firebase
    import FirebaseFirestore

    class ProductListVC: UIViewController {

        @IBOutlet weak var productListTableView: UITableView!

        var productInventory: [ProductList] = []
        var productSetup: [ProductList] = []
        var selectedProduct: Product?

        override func viewWillAppear(_ animated: Bool) {
            super.viewWillAppear(animated)
        }

        override func viewDidLoad() {
            super.viewDidLoad()

            productListTableView.dataSource = self
            productListTableView.delegate = self
            searchBar.delegate = self

            fetchProducts { (products) in
                self.productSetup = products
                self.productListTableView.reloadData()
            }

        }
       func fetchProducts(_ completion: @escaping ([ProductList]) -> Void) {
           let ref = Firestore.firestore().collection("products")
      ref.addSnapshotListener { (snapshot, error) in
                guard error == nil, let snapshot = snapshot, !snapshot.isEmpty else {
                    return
                }
                completion(snapshot.documents.compactMap( {ProductList(dictionary: $0.data())} ))
            }
        }

            override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
            if let vc = segue.destination as? MoreInforVC {
            vc.product = self.selectedProduct
            }
        }
    }

    extension ProductListVC: UITableViewDelegate, UITableViewDataSource {
        func numberOfSections(in tableView: UITableView) -> Int {
            return 1
        }
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

            return productSetup.count
        }

        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            guard let cell = tableView.dequeueReusableCell(withIdentifier: "ProductListCell") as?
    ProductListCell else { return UITableViewCell() }

             cell.configure(withProduct: productSetup[indexPath.row])

             cell.delegate = self

          return cell
      }

  }

  extension ProductListController: ProductListCellDelegate {
      func onTouchInfoButton(from cell: ProductListCell) {
          self.selectedProduct = cell.product
          self.performSegue(withIdentifier: "YourSegueIdentifier", sender: self)
      }
  }

这篇关于如何将数据从TableViewCell中的按钮传递到View Controller?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆