首页 > 解决方案 > 如何使用 int 值将项目添加到表视图

问题描述

如何将数字添加到表格单元格并将数字添加到总标签?w当我添加 ps2 之类的项目时,如何将价格添加到表格单元格并将其添加到我的总标签中?这是我 3 周以来一直试图解决的问题。

到目前为止我的表:

我的桌子

我的 ViewController.swift 代码:

import UIKit

class ViewController: UIViewController, UITableViewDataSource {

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell")! //1.

        let text = data[indexPath.row] //2.

        cell.textLabel?.text = text //3.

        return cell //4.
    }


    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.dataSource = self
    }

    @IBOutlet weak var totalLabel: UILabel!

    var data = ["pizza"]
    var total = 0


    @IBAction func addButton(_ sender: Any) {

        let alert = UIAlertController(title: "New Name", message: "Add a new name", preferredStyle: .alert)

        let saveAction = UIAlertAction(title: "Spice", style: .default) { [unowned self] action in
            guard let textField = alert.textFields?.first, let nameToSave = textField.text else { return }

            self.total += 2000
            self.totalLabel.text = "Total Bill is: $\(self.total)"

            self.data.append(nameToSave)
            self.tableView.reloadData()                       
        }

        let cancelAction = UIAlertAction(title: "Cancel", style: .default)


        alert.addTextField()

        alert.addAction(saveAction)
        alert.addAction(cancelAction)

        present(alert, animated: true)
    }

}

标签: iosswiftuitableview

解决方案


简单的解决方案:

  • 例如,创建适当的数据模型

    struct Model {
        let name : String
        let price : Double
    }
    
  • 在控制器中创建data

    var data = [Model]()
    
  • 例如,在 viewDidLoad 中填充数据源数组

    override func viewDidLoad() {
       super.viewDidLoad()
    
       data = [Model(name: "Pizza", price: 4.99), Model(name: "Burger", price: 2.99)]
       tableView.dataSource = self
    }
    
  • 每当您重新加载表格视图时,总结价格

    totalLabel.text = String(data.map{$0.price}.reduce(0.0, +))
    

推荐阅读