Ios 从UITableView中的标签快速计数

Ios 从UITableView中的标签快速计数,ios,swift,uitableview,uilabel,nsuserdefaults,Ios,Swift,Uitableview,Uilabel,Nsuserdefaults,我问了一个类似的问题,但我需要帮助 我有UIViewController,它包含UITableView,UILabel,在一个表下显示总价 在UITableViewCell中,我有UIImage来显示照片,UILabel来显示数量,+-UIButton和UILabel来显示价格 我从UserDefaults 我想在totalUILabeltotal price表单数量x价格中显示 每个UITableViewCell 按+或-ui按钮时需要更改ui标签的数量 来自UIViewController的

我问了一个类似的问题,但我需要帮助

我有
UIViewController
,它包含
UITableView
UILabel
,在一个表下显示总价

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

我从
UserDefaults

我想在total
UILabel
total price表单数量x价格中显示 每个
UITableViewCell

按+或-
ui按钮时
需要更改
ui标签
的数量

来自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($0.trimmingCharacters(in: .whitespaces)) }
        var sum = val.reduce(0, +)
        print("sum\(sum)")

        let prrr = price.components(separatedBy: "").compactMap { Int($0.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
,并将其显示在total
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(uSender:ui按钮)
中执行此操作,将其委托给ViewController并在那里执行此操作。 在
视图中将出现
,记住从用户默认值重新加载数据,刷新表视图

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

class Order {
  var name: String
  var price: Double
  var quantity: Int
}
-为tableviewcell指定一个委托:

协议OrderTableViewCellDelegate:类{ 按下func plusButtonPressed(u单元格:OrderTableViewCell) }

在“表格视图”单元类中

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()
     }
}
视图中将出现

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
}

嗨,我理解对了吗?TableViewCell类:导入UIKit协议OrderTableViewCellDelegate:类{func plusButtonPressed(cell:TestTableViewCell)}弱变量委托:OrderTableViewCellDelegate@ViewCintroller类中的iAction func plusBtn(uSender:UIButton){delegate?.plusButtonPressed(self)}弱变量委托:TestTableViewCell?扩展TestTABLEVC:OrderTableViewCellDelegate{func plusButtonPressed(cell:TestTableViewCell){let indexath=self.tableViewT.indexath(for:cell)var item=self.loadedCart[(indexath?.row)!]var oldValue=UserDefaults.standard.array(forKey:“car”)item.updateValue((delegate?.qntLbl.text)!,forKey:“qty”)self.tableViewT.beginUpdates()self.tableViewT.reloadRows(位于:[indexPath!],带:。automatic)self.tableViewT.endUpdates()?您可以用格式化的代码编辑注释吗?并且必须将单元格的委托分配给VC。
tableView中的
cell.delegate=self
(\uTableView:UITableView,cellAtIndexPath)
methodIm添加有问题的格式化代码并添加到cellAtIndexPath
cell.delegate=self
我更新了我的答案。你不需要在VC中创建委托。查看添加的代码了解详细信息。