ios - 从 UITableView 中的 Label 快速计数

标签 ios swift uitableview uilabel nsuserdefaults

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

我有UIViewController其中包含 UITableView , UILabel在表格下方显示总价。

UITableViewCell我有UIImage显示照片,UILabel显示数量,+ - UIButton的和UILabel显示价格。

我从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($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并显示总计 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) 中执行此操作,将其委托(delegate)给 ViewController 并在那里完成工作。 在viewWillAppear中,记住从用户默认值中重新加载数据,刷新 TableView 。

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

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

-给 tableviewcell 一个委托(delegate):

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

在 TableView 单元格类中,

class OrderTableView {
   ... your view outlets go here

   weak delegate: OrderTableViewCellDelegate?

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

- 在 View Controller 中,记得实现 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()
}

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

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
}

关于ios - 从 UITableView 中的 Label 快速计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50123684/

相关文章:

ios - UIScrollViewKeyboardDismissModeOnDrag 当没有滚动不起作用时

swift - 如何在Swift中使用animationDidStop

ios - 停止 tableView 滚动

ios - iPhone 上的谷歌翻译 API

ios - 如何使用 NSJSONSerialization 区分 0/1 和 false/true?

ios - 使用 AVPlayer 实现流畅的视频擦洗

ios - 在 UITableViewDataSource 类中使用 UITableViewController 逻辑

swift - 自定义ui table view cell swift如何显示大量标签?

iphone - textField 应在调用方法后立即更新

iOS 12,Xcode 10 : UIView setNeedsDisplay(_:) seems to be broken