Как передать данные по нажатой кнопке в ячейке в другое представление таблицы? - PullRequest
3 голосов
/ 31 октября 2019

Во-первых: как я смогу передавать данные из ячейки ItemVC в CartVC on по кнопке Clicked (кнопка добавления в корзину (ATC)) в выбранной ячейке, поскольку я не пытаюсь использовать didSelectRowAt для передачи данных вCartVC. но ATC btn для передачи данных ячеек в CartVC

мой Segue из ItemVC в CartVC находится в BarButtonItem (cartBtn), поэтому я не хочу переходить к CartVc при нажатии кнопки ATC, но только передатьданные выбранных элементов в CartVC при нажатии на ATC

Во-вторых, как я смогу передать значение приращения / уменьшения в lblQty в CartVC при нажатии на ATC, чтобы иметь возможность представить более точныйИтого

enter image description here

import UIKit
import SDWebImage
import Firebase


class ItemCell: UITableViewCell {

    weak var items: Items!

    @IBOutlet weak var name: UILabel!
    @IBOutlet weak var category: UILabel!
    @IBOutlet weak var productImage: UIImageView!
    @IBOutlet weak var weight: UILabel!
    @IBOutlet weak var price: UILabel!

    @IBOutlet weak var lblQty: UILabel!

    @IBOutlet weak var addToCart: RoundButton!
    @IBOutlet weak var plusBtn: RoundButton!
    @IBOutlet weak var minusBtn: RoundButton!

    func configure(withItems : Items) {
        name.text = product.name
        category.text = items.category
        image.sd_setImage(with: URL(string: items.image))
        price.text = items.price
        weight.text = items.weight
    }

}

import UIKit
import Firebase
import FirebaseFirestore

class ItemViewController: UITableViewController {

    @IBOutlet weak var cartBtn: BarButtonItem!!
    @IBOutlet weak var tableView: UITableView!

    var itemSetup: [Items] = []

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.delegate = self

        fetchItems { (items) in
            self.itemSetup = items.sorted
            self.tableView.reloadData()
        }

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

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let vc = segue.destination as? CartViewController {
            vc.items = self.itemSetup
        }
    }
    @objc func plusItem(_ sender: UIButton) {
        let currentCount = self.itemSetup[sender.tag].count
        if currentCount > 9 {
            return
        }
        self.itemSetup[sender.tag].count = currentCount + 1
        if let currentCell = self.tableView.cellForRow(at: IndexPath(row: sender.tag, section: 0)) as? ItemCell {
            currentCell.lblQty.text = "\(self.itemSetup[sender.tag].count)"
        }
    }

    //Function to decrement item count
    @objc func minusItem(_ sender: UIButton) {
        let currentCount = self.itemSetup[sender.tag].count
            if !(currentCount - 1 >= 0) {
            //Usually item count will not be negative value
            return
        }
        self.itemSetup[sender.tag].count = currentCount - 1
        if let currentCell = self.tableView.cellForRow(at: IndexPath(row: sender.tag, section: 0)) as? ItemCell {
            currentCell.lblQty.text = "\(self.itemSetup[sender.tag].count)"
        }
    }

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

        return itemSetup.count
    }

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

        cell.configure(withItem: itemSetup[indexPath.row])

        cell.lblQty.text = "\(self.imageSetup[indexPath.row].count)"
        cell.plusBtn.tag = indexPath.row
        cell.plusBtn.addTarget(self, action: #selector(self.plusItem(_:)), for: .touchUpInside)
        cell.minusBtn.tag = indexPath.row
        cell.minusBtn.addTarget(self, action: #selector(self.minusItem(_:)), for: .touchUpInside)

        return cell
    }

}

class CartViewController: UIViewController {

    var items: Items!
    @IBOutlet weak var cartTableView: UITableView!

     override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        cartTableView.dataSource = self
        cartTableView.delegate = self
    }

}

extension CartViewController: UITableViewDataSource, UITableViewDelegate {

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return Cart.currentCart.cartItems.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CartCell", for: indexPath) as! CartCell

        let cart = Cart.currentCart.CartItems[indexPath.row]
        cell.qty.text = "\(cart.qty)"
        cell.lblMealName.text = "\(cart.items.category): \(cart.items.name)"
        cell.lblSubTotal.text = "$\(cart.items.price1 * Float(cart.qty))"

        cell.imageUrl                             // can't figure out how to pass image

        return cell
    }
}

import Foundation

class CartItem {

    var items: Items
    var qty: Int

    init(items: Items, qty: Int) {
        self.items = items
        self.qty = qty
    }
}

class Cart {
    static let currentCart = Cart()
    var cartItems = [CartItem]()
}

1 Ответ

2 голосов
/ 31 октября 2019

Просто создайте протокол для создания делегата и назначьте его вашему классу корзины при инициализации ячейки

protocol ItemCellDelegate {
    func itemCell(didTapButton button: UIButton)
}    

Затем укажите свойство делегата в ItemCell

class ItemCell {
    weak var delegate: ItemCellDelegate?
    ...
    // Then call the delegate method when the buttons is tapped.
    func buttonTapped() {
        delegate?.itemCell(didTapButton: theCellsButton)
    }
}

Затемзаставить вашу корзину соответствовать делегату

extension Cart: ItemCellDelegate {
    func itemCell(didTapButton button: UIButton) {
        // Do you stuff with button, or any other data you want to pass in
    }
}

Затем установите делегата до того, как ячейка будет возвращена.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "CartCell", for: indexPath) as! CartCell

    let cart = Cart.currentCart.CartItems[indexPath.row]
    cell.qty.text = "\(cart.qty)"
    cell.lblMealName.text = "\(cart.items.category): \(cart.items.name)"
    cell.lblSubTotal.text = "$\(cart.items.price1 * Float(cart.qty))"

    cell.delegate = Cart.currentCart //You should rename this static var to just 'current'

    return cell
}
...