2

I am building a food ordering app. In which, there are increment and decrement buttons and a UILabel to display quantity. I want to update the quantity label on increment and decrement buttons click. Image of which is attached.

enter image description here

A snippet of My ViewController is

protocol GondolaTableViewCellDelegate: class {
    func tableViewCellAddToCart(_ sender: ItemDetailTableViewCell)
    func tableViewCellIncrement(_ sender: ItemDetailTableViewCell)
    func tableViewCellDecrement(_ sender: ItemDetailTableViewCell)
    var tableViewCellQuantity: String { get set }
}

class ItemDetailTableViewCell: UITableViewCell {
    //itemTableCell

    var quantity = 1

    @IBOutlet weak var itemNameLabelCell: UILabel!
    @IBOutlet weak var itemDescLabelCell: UILabel!
    @IBOutlet weak var itemPriceLabelCell: UILabel!
    @IBOutlet weak var itemQuantityLabelCell: UILabel!
    @IBOutlet weak var itemDecrementButton: UIButton!
    @IBOutlet weak var itemIncrementButton: UIButton!
    @IBOutlet weak var addToCartButton: UIButton!

    weak var delegate: GondolaTableViewCellDelegate?

    @IBAction func addToCartCellButton(_ sender: Any) {
        delegate?.tableViewCellAddToCart(self)

        //print("Neck, Angel Memory")
    }
    @IBAction func itemIncrementButtonCell(_ sender: Any) {
        delegate?.tableViewCellIncrement(self)

        //quantity  = quantity+1
        //itemQuantityLabelCell.text = "\(quantity)"
    }
    @IBAction func itemDecrementButtonCell(_ sender: Any) {
        delegate?.tableViewCellDecrement(self)

//        if quantity == 1 {
//            //toastNeck(message: "Min. quantity should be 1")
//        }else if quantity >= 2 {
//            //quantity  = quantity-1
//        }
        //itemQuantityLabelCell.text = "\(quantity)"
    }

}

class AllItemViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, GondolaTableViewCellDelegate {
    var tableViewCellQuantity: String = ""



    @IBOutlet weak var allItemImageHeader: UIImageView!
    @IBOutlet weak var allItemTableView: UITableView!
    @IBOutlet weak var allItemLabel: UILabel!
    @IBOutlet weak var visualEffect: UIVisualEffectView!
    @IBOutlet weak var itemsTableView: UITableView!
    @IBOutlet weak var itemDetailLabel: UILabel!
    @IBOutlet weak var cartItemLabel: UILabel!

    var storeItem = [StoreItem]()
    var allItem = [ItemDetaill]()
    var quantityArray: [Int] = []

    var selectedIndex: Int!

    var storeId: String = ""
    var storeCatId: String = ""
    var storeName: String = ""
    var quantity = 1

    override func viewDidLoad() {
        super.viewDidLoad()

        for i in 0 ..< 100 {
            quantityArray.append(2)
        }

        allItemTableView.delegate = self
        allItemTableView.dataSource = self
        itemsTableView.delegate = self
        itemsTableView.dataSource = self


    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return tableView === allItemTableView ? storeItem.count : allItem.count
    }

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

        return 1 //storeItem.count
    }

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 5
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let header = UIView()
        header.backgroundColor = UIColor.white
        return header
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return tableView === allItemTableView ? 56 : 100
    }

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

        if tableView == allItemTableView {
            let storeCell = allItemTableView.dequeueReusableCell(withIdentifier: "allItemCell", for: indexPath) as! AllItemTableViewCell

            return storeCell
        }else {
            let itemCell = itemsTableView.dequeueReusableCell(withIdentifier: "itemTableCell", for: indexPath) as! ItemDetailTableViewCell
            itemCell.itemNameLabelCell.text = allItem[indexPath.section].item_name
            itemCell.itemDescLabelCell.text = allItem[indexPath.section].item_desc
            itemCell.itemPriceLabelCell.text = "₹" + allItem[indexPath.section].item_net_price
            itemCell.delegate = self
            itemCell.addToCartButton.tag = indexPath.section
            itemCell.addToCartButton.addTarget(self, action: #selector(addToCarts(_:)), for: .touchUpInside)
            itemCell.itemIncrementButton.tag = indexPath.section
            itemCell.itemIncrementButton.addTarget(self, action: #selector(increment(_:)), for: .touchUpInside)
            itemCell.itemDecrementButton.tag = indexPath.section
            itemCell.itemDecrementButton.addTarget(self, action: #selector(decrement(_:)), for: .touchUpInside)

            return itemCell
        }

    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        selectedIndex = indexPath.section
        if tableView == allItemTableView {

        }else {
            let itemCell = itemsTableView.cellForRow(at: indexPath)

            print("Will Work")
        }

    }

    @objc func increment(_ sender: UIButton) {
        quantity = quantity + 1
        tableViewCellQuantity = "\(quantity)"
        //let newQuantity = quantityArray[sender.tag] + 1
        //self.quantityArray.replaceSubrange(sender.tag, with: newQuantity)
        itemsTableView.reloadData()
    }

    @objc func decrement(_ sender: UIButton) {
        if quantity == 1 {
            toastNeck(message: "Min. quantity should be 1")
        }else if quantity >= 2 {
            quantity  = quantity - 1
        }
        tableViewCellQuantity = "\(quantity)"
        itemsTableView.reloadData()
    }

    @objc func addToCarts(_ sender: UIButton) {
        if sender.tag == 0 {
            print(storeItem[sender.tag].item_name)
        }
    }


    func tableViewCellAddToCart(_ sender: ItemDetailTableViewCell) {
        guard let tappedIndexPath = itemsTableView.indexPath(for: sender) else {
            return
        }

        print(allItem[tappedIndexPath.section].item_name)
    }

    func tableViewCellIncrement(_ sender: ItemDetailTableViewCell) {
        guard let tappedIndexPath = itemsTableView.indexPath(for: sender) else {
            return
        }

        print(allItem[tappedIndexPath.section].created_date)
        quantity = quantity + 1
        tableViewCellQuantity = "\(quantity)"
        //let newQuantity = quantityArray[tappedIndexPath.section] + 1
        //self.quantityArray.replaceSubrange(tappedIndexPath.count, with: <#T##Collection#>)

    }

    func tableViewCellDecrement(_ sender: ItemDetailTableViewCell) {
        guard let tappedIndexPath = itemsTableView.indexPath(for: sender) else {
            return
        }
        if quantity == 1 {
            toastNeck(message: "Min. quantity should be 1")
        }else if quantity >= 2 {
            quantity  = quantity - 1
        }
        tableViewCellQuantity = "\(quantity)"
        itemsTableView.reloadData()

        print(allItem[tappedIndexPath.section].id)
    }

    func tableViewCellQuantity(_ sender: ItemDetailTableViewCell) {

    }
}

However I am able to detect the button clicks through protocols, but unable to update the UILabel.

Also I need to store the added items into data model class and have to be different values of different items, means each item should store diffrent quantities.

There is a similar question here but its not working.

Please let me know if anyone need any more details.

Neck
  • 611
  • 1
  • 7
  • 21
  • You need to have Model which contains quantity, When user clicks button increase the quantity and then reloadCellAtIndexPath – Morteza Soleimani Jun 15 '18 at 04:44
  • https://stackoverflow.com/questions/35402287/how-to-add-json-and-stepper-value-store-in-using-button-click-event-nsmutablearr – Jigar Jun 15 '18 at 04:45
  • @JigarDarji its in Objective-C, I need for swift 4. – Neck Jun 15 '18 at 04:48
  • The duplicate uses a stepper but the procedure is basically the same. – vadian Jun 15 '18 at 04:56
  • you have create IBActions for button by using interface builder and Inside cellForRowAt you programatically added the action both are doin same thing but here we want either one way. So remove IBActions from UITableViewCell class @Neck – Ganesh Manickam Jun 15 '18 at 05:36
  • @GaneshManickam actually I am trying both cases, whichever works I'll keep that. But by removing IBActions from cell class is not solving the issue. same error. – Neck Jun 15 '18 at 05:46
  • Is it possible to share your project code so that I can have a look into it and help you out. @Neck – Ganesh Manickam Jun 15 '18 at 05:50
  • @GaneshManickam yes, I can share my VC. Tell me where? – Neck Jun 15 '18 at 05:57
  • Will need your UI also i.e XIB or Storyboard. Code you can paste here https://pastebin.com and share. Or else you can zip everything and send it across to me. I can give you my email id if needed – Ganesh Manickam Jun 15 '18 at 06:01
  • @GaneshManickam I have pasted my full VC [https://pastebin.com/1VtDURtV] – Neck Jun 15 '18 at 06:24
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/173192/discussion-between-ganesh-manickam-and-neck). – Ganesh Manickam Jun 15 '18 at 06:26
  • hey **Neck** how were you able to pass data to your cart when pressing the "Add to Cart" button with increase and decrease buttons in each cell im stuck on how to pass to data from each cell to the cart. – Evelyn Oct 26 '19 at 12:57

1 Answers1

0

Try this :

@objc func increment(_ sender: UIButton) {
       if let cell = sender.superview?.superview as? YourCellClass {
           let indexPath = tbl_songsInfo.indexPath(for: cell)
           //Do whatever you want

        quantity = quantity + 1
        tableViewCellQuantity = "\(quantity)"
        //let newQuantity = quantityArray[sender.tag] + 1
        //self.quantityArray.replaceSubrange(sender.tag, with: newQuantity)
        itemsTableView.reloadData()

        }

    }

check out this link

Pratik Prajapati
  • 1,137
  • 1
  • 13
  • 26