Быстрый подсчет от метки в UITableView - PullRequest
0 голосов
/ 01 мая 2018

Я задал похожий вопрос, но мне нужна помощь

У меня есть 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)
}
}

1 Ответ

0 голосов
/ 02 мая 2018

По сути, вы просто изменили переменные в памяти. Вам необходимо записать эти новые значения обратно в пользовательские настройки по умолчанию, чтобы сохранить их.

Вы можете сделать это в func plusBtn(_ sender: UIButton), делегировать его в ViewController и выполнить работу там. И в viewWillAppear не забудьте перезагрузить данные из пользовательского по умолчанию, обновить представление таблицы.

Вот несколько советов: - Создать класс модели для хранения данных. Например:

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

- дать делегату в виде таблицы:

протокол OrderTableViewCellDelegate: class { 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
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...