【问题标题】:Swift counting from Label in UITableView从 UITableView 中的标签快速计数
【发布时间】:2018-10-11 21:59:56
【问题描述】:

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

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

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($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)
}
}

【问题讨论】:

    标签: ios swift uitableview uilabel nsuserdefaults


    【解决方案1】:

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

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

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

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

    - 给 tableviewcell 一个委托:

    协议 OrderTableViewCellDelegate: 类 { func plusButtonPressed(_ cell: 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()
         }
    }
    

    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
    }
    

    【讨论】:

    • 嗨,我理解正确吗? TableViewCell 类:导入 UIKit 协议 OrderTableViewCellDelegate:类 { func plusButtonPressed(_ cell: TestTableViewCell) } 弱 var 委托:OrderTableViewCellDelegate? @IBAction func plusBtn(_ sender: UIButton) { delegate?.plusButtonPressed(self) }
    • 在 ViewCintroller 类中:弱 var 委托:TestTableViewCell?扩展 TestTABLEVC: OrderTableViewCellDelegate { func plusButtonPressed(_ cell: TestTableViewCell) { let indexPath = self.tableViewT.indexPath(for: cell) var item = self.loadedCart[(indexPath?.row)!] var oldValue = UserDefaults.standard.array (forKey: "car") item.updateValue((delegate?.qntLbl.text)!, forKey: "qty") self.tableViewT.beginUpdates() self.tableViewT.reloadRows(at: [indexPath!], with: .自动)self.tableViewT.endUpdates() ?
    • 你能用格式化的代码编辑你的 cmets 吗?并且还必须将单元格的代表分配给 VC。 cell.delegate = selftableView(_ tableView: UITableView, cellAtIndexPath) 方法中
    • 我添加有问题的格式化代码并添加到 cellAtIndexPath cell.delegate = self
    • 我更新了我的答案。您不需要在 VC 中创建委托。查看添加的代码了解详情。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-16
    • 2015-01-15
    相关资源
    最近更新 更多