Swift 从 UITableView 中的 Label 开始计数

Swift counting from Label in UITableView

我问过类似的问题,但我需要帮助

我有 UIViewController,其中包含 UITableViewUILabel 在 table 下以显示总价。

UITableViewCell中我有UIImage显示照片,UILabel显示数量,+ - UIButtonUILabel显示价格.

我从UserDefaults

取数据

我要显示总价UILabel总价形式数量x价格 每个 UITableViewCell

的数量

当按+或-时UIButton需要用数量

改变UILabel

来自 UIViewController 的代码:

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TetTableViewCell    
        var item = loadedCart[indexPath.row]
        cell.nameLbl?.text = item["name"] //as? String
        cell.priceLbl.text = item["price"] //as? String
        cell.qntUserDef = Int(item["qty"]!)!
        updateTotal()
  return cell
  }

   func updateTotal() {
   for item in loadedCart {

        var qnt = item["qty"] ?? ""
        var price = item["price"] ?? ""

        let val = qnt.components(separatedBy: "").compactMap { Int([=11=].trimmingCharacters(in: .whitespaces)) }
        var sum = val.reduce(0, +)
        print("sum\(sum)")

        let prrr = price.components(separatedBy: "").compactMap { Int([=11=].trimmingCharacters(in: .whitespaces)) }
        let sumpri = prrr.reduce(0, +)
        print("sumpri\(sumpri)")


        qntUser += (sum * sumpri) ?? 0


        if item["qty"] == nil {
            self.totalSummLbl.text = "\(0)"
        }

        if item["qty"]?.count == 0 {
            totalSummLbl.text = "\(0)"
            print("total\(totalSummLbl.text)")
        } else {
            totalSummLbl.text = "\(qntUser)"

        }
    }

}

来自 UITableViewCell 的代码:

var lCart = UserDefaults.standard.array(forKey: "car") as? [[String: String]] ?? []

var qntUserDef: Int = 0
 @IBAction func plusBtn(_ sender: UIButton) {
 for item in lCart {
        qntLbl.text = item["qty"]
    }
    qntUserDef += 1
    qntLbl.text = "\(qntUserDef)"
    print("tettttt-\(qntUserDef)")
 }

通过这个我已经实现了数量 UILabel 的改变,但是当我进入另一个并返回时 - 不要保存并且不显示新的数量和总和 UILabel

如何更改代码以将数据重新保存到 UserDefaults 并在按 + 或 - 时显示总计 UILabel

给大和回答:

VC代码:

Class : 

 weak var delegate: TestTableViewCell?

  extension TestTABLEVC: OrderTableViewCellDelegate {
 func plusButtonPressed(_ cell: TestTableViewCell) {
    let indexPath = self.tableViewT.indexPath(for: cell)
    var item = loadedCart[(indexPath?.row)!]
        item["qty"] = "\(cell.qntUserDef)"

        // write the data back to user default
    var oldValue = UserDefaults.standard.array(forKey: "car")
    item.updateValue(cell.qntLbl.text!, forKey: "qty")

        // reload this cell
        self.tableViewT.beginUpdates()
    self.tableViewT.reloadRows(at: [indexPath!], with: .automatic)
    self.tableViewT.endUpdates()
}
}

来自 TableViewCell 的代码:

import UIKit

  protocol OrderTableViewCellDelegate: class {
   func plusButtonPressed(_ cell: TestTableViewCell)

   }

 class TestTableViewCell: UITableViewCell {

weak var delegate: OrderTableViewCellDelegate?
 @IBAction func plusBtn(_ sender: UIButton) {
    delegate?.plusButtonPressed(self)
}
}

基本上您所做的只是更改内存中的变量。您需要将这些新值写回用户默认值以保存它。

您可以在 func plusBtn(_ sender: UIButton) 中执行此操作,将其委派给 ViewController 并在那里完成工作。 在 viewWillAppear 中,记得从用户默认值重新加载数据,刷新 table 视图。

有一些提示: - 创建一个模型 class 来保存数据。例如:

class Order {
  var name: String
  var price: Double
  var quantity: Int
}

- 给 tableviewcell 一个委托:

协议 OrderTableViewCellDelegate: class { func plusButtonPressed(_ cell: OrderTableViewCell) }

在 table 视图单元格中 class,

class OrderTableView {
   ... your view outlets go here

   weak delegate: OrderTableViewCellDelegate?

   @IBAction func plusBtn(_ sender: UIButton) {
       delegate?.plusButtonPressed(self)
   }
}

- 在视图控制器中,记得实现 OrderTableViewCellDelegate。

extension class CartViewController: OrderTableViewCellDelegate {
     override func plusButtonPressed(_ cell: OrderTableViewCell) {
        let indexPath = self.tableView.indexPathForCell(cell)
        let item = self.items[indexPath.row]
        item.quantity += 1

        // write the data back to user default
        ....

        // reload this cell
        self.tableView.beginUpdates()
        self.tableView.reloadCellAtIndexes([indexPath], animation: .automatic)
        self.tableView.endUpdates()
     }
}

viewWillAppear,

func viewWillAppear(_animated: Bool) {
    super.viewWillAppear(animated)

    //reload the data from user default
    self.items = read and parse the data from user default to a list of Order models
    //reload the table view
    self.tableView.reloadData()
}

更新:设置单元格的委托。

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

        // configure your cell

        // IMPORTANT: set the cell's delegate to this VC
        cell.delegate = self.

        return cell
}