【问题标题】:How pass data from button in TableViewCell to View Controller?如何将数据从 TableViewCell 中的按钮传递到视图控制器?
【发布时间】:2020-02-05 07:59:53
【问题描述】:

我有 2 个 ViewController,其中一个称为 ProductListVC,另一个是 MoreInfoVC。我在 ProductListViewController 上有一个 tableView,它显示了多个标签和按钮的单元格。

MoreInfoVC 是一个模态弹出式 VC,带有几个标签用于品牌、名称和描述。我将所有数据都存储在 Firestore 中,并且已经创建了类 (ProductList) 来帮助从 Cloud Firestore 检索在 tableview 中呈现数据的数据。

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

现在我可以使用 didSelectRowAt 方法或在 prepare segue 方法中使用 indexPathForSelectedRow 轻松完成此操作。但是这两种情况都需要我点击单元格本身而不是按钮。

我如何能够通过 MoreInfo 按钮将来自单个 tableview 单元格的数据传递到 MoreInfoVC。我认为我走在正确的道路上,因为我的 MoreInfoVC 似乎正在传递数据,但目前正在显示这一点


    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)
      }
  }

【问题讨论】:

    标签: swift uitableview button google-cloud-firestore


    【解决方案1】:

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

    点击该按钮后,通过delegateclosureProductListVC 连接以获取所选产品。

    更新

    使用委托: 更新您的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 中

    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)
          }
      }
    

    【讨论】:

    猜你喜欢
    • 2017-11-30
    • 2018-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-14
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    相关资源
    最近更新 更多