首页 > 解决方案 > 将对象从 UITableView 发送到另一个没有全局数组的 UITableView

问题描述

我需要一些帮助才能将数据从 TableView 传递到另一个而不使用全局数组。当我按下按钮时,我想将产品从 UITableView (ProductsTableView) 发送到另一个 UITableView (CartTableView),但问题是我在这两个表之间没有 segue。如何将所选产品从我拥有 ProductsTableView 的第一个 VC 发送到我的 CartTableView 所在的第二个 VC?

这是我的代码:

 // First VC
 class ProductsViewController: UIViewController{

 @IBOutlet weak var productsTableView: UITableView!

        // Function to add the product into the cart
            @IBAction func addProductToCartButton(_ sender: UIButton) {

                // Start animation region
                let buttonPosition : CGPoint = sender.convert(sender.bounds.origin, to: self.productsTableView)
                let indexPath = self.productsTableView.indexPathForRow(at: buttonPosition)!
                let cell = productsTableView.cellForRow(at: indexPath) as! ProductTableViewCell
                let imageViewPosition : CGPoint = cell.productImageView.convert(cell.productImageView.bounds.origin, to: self.view)
                let imgViewTemp = UIImageView(frame: CGRect(x: imageViewPosition.x, y: imageViewPosition.y, width: cell.productImageView.frame.size.width, height: cell.productImageView.frame.size.height))
                imgViewTemp.image = cell.productImageView.image
                animationProduct(tempView: imgViewTemp)
                // End animation region
                // Start appending product to cart
                // TODO: add the logic for append here
                // End appending product to cart
                showAlertWith(title: "Added", message: "Product added with success.")
            }

       // "Product" is my entity from Core Data     
      func appendProductToCartList(product: Product){ 
      }

    // Function to send details about a product from this VC to another VC
        override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

          if let selectedIndexPath = productsTableView.indexPathForSelectedRow {
                let cartVC: CartViewController = segue.destination as! CartViewController
                cartVC.cartProductsArray = [productsArray[selectedIndexPath.row]]
            }
       }
 }
 // Second VC
 class CartViewController: UIViewController {
      @IBOutlet weak var cartTableView: UITableView!
      var cartProductsArray = [Product]()
 }

这是我的界面的 GIF:

在此处输入图像描述

谢谢 !

标签: iosswiftuitableviewswift4

解决方案


推荐阅读