1

i have a VC name RestaurantViewController it has custom cell for itemName ItemPrice and there are three button + , - and add their actions are in customCellClass now when a user select the quantity by setting with plus/minus and then hit the add button the whole data should go to the CartVC but not push until user selects the cart icon on main menu.

the RestaurantVC looks like thisenter image description here

currently i'm using the blockClosure to pass data

 //assign item name to cell
    let selectedDictName = restMenu[indexPath.row] as! NSDictionary
    print("the selected dict ", selectedDictName)
    cell.itemNameLabel.text = selectedDictName.value(forKey: "ItemName") as! String

    // assign item price to cell
    let selectedDictPrice = restMenu[indexPath.row] as! NSDictionary
    cell.itemPriceLabel.text = "Price: \(selectedDictPrice.value(forKey: "ItemPrice") as! String)"

    // pass ItemName and ItemPrice by blockClosure
    if blockClosure != nil{
        blockClosure(selectedDictName.value(forKey: "ItemName") as! String, selectedDictPrice.value(forKey: "ItemPrice") as! String )
    }

but this pass all values corresponding the selected restaurant at before loading the cell

how can i pass data and then further attach the item quantity with it? it will be very helpful for my final semester project

Shivam Tripathi
  • 1,405
  • 3
  • 19
  • 37
Gurjit Singh
  • 137
  • 10
  • 1
    Are you familiar with protocols and delegate? Give this a look: https://stackoverflow.com/a/25792213/4427884 – Codetard May 11 '18 at 05:55
  • You want pass data from `RestaurantViewController` to custom cell? I think you are already doing by setting `cell.itemNameLabel.text`.. Can you explain your problem little more? – Ankit Jayaswal May 11 '18 at 05:57
  • with this cell.itemNameLabel.text the last object value in dictionary is assigned to the closure block not the one whose button is clicked – Gurjit Singh May 11 '18 at 06:12
  • Shouldn't the question be 'passing values form custom tableViewCell to ViewController'? – Tejas K Dec 03 '19 at 07:49

1 Answers1

3

Follow Below Code:- Using Protocol Delegate

//1
//Create protocol

protocol TableViewCellDelegate {
    func addTapped(cell: TableViewCell)
}

//2
//Create instance
class TableViewCell: UITableViewCell {

var delegate: TableViewCellDelegate?

….

@IBAction func addAction(_ sender: Any) {
    delegate?.addTapped(cell: self)
}
}


//3

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

    // create a new cell if needed or reuse an old one
    let cell: TableViewCell = tableView.dequeueReusableCell(withIdentifier: “cell”, for: indexPath) as! TableViewCell
    cell.delegate = self
}

 //4
extension ViewController: TableViewCellDelegate {
func addTapped(cell: TableViewCell) {

 }
}
Manish Mahajan
  • 2,062
  • 1
  • 13
  • 19