【发布时间】:2018-10-11 21:59:56
【问题描述】:
我问了一个类似的问题,但我需要帮助
我有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)
}
}
【问题讨论】:
标签: ios swift uitableview uilabel nsuserdefaults