Я задал похожий вопрос, но мне нужна помощь
У меня есть 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)
}
}