![](/img/trans.png)
[英]How to set data from ViewController to UITableView custom Cell
[英]how to pass Values from ViewController to UITableView custom cell class
我有一個VC名稱RestaurantViewController
它具有用於itemName ItemPrice的自定義單元格,並且有三個按鈕+,-,並且當用戶通過使用加/減設置選擇數量然后單擊添加按鈕整個數據時,將它們的動作添加到customCellClass中應該轉到CartVC
但不要推送,直到用戶在主菜單上選擇了購物車圖標。
目前我正在使用blockClosure傳遞數據
//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 )
}
但這會在加載單元格之前傳遞與所選餐廳對應的所有值
我如何傳遞數據,然后進一步附加項目數量? 這將對我的最后一個學期項目非常有幫助
請遵循以下代碼:-使用協議委托
//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) {
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.