ios - 如何使用 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)
}
}
解决方案
简单的解决方案:
例如,创建适当的数据模型
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, +))
推荐阅读
- css - 网格自动调整最后一项高于而不是低于
- angular8 - 我如何将 rxjs debounceTime 和 distinctUntilChanged 与角度输入事件(例如,单击或输入)一起使用
- javascript - JSX 中的布尔复选框值不起作用
- qlikview - 在 qlik 意义上更改分布图的颜色
- javascript - mapbox-gl 未聚集的点重叠为一个圆圈
- c# - 如何在 c# linq 中的对象内为对象创建 where 条件?
- javascript - 在应用程序启动时运行计算代码 html 表
- c++ - quit() 函数中的 C++ 可能的范围问题
- office365 - Office 365 导入作业 PST Rest API
- python - 使用 numpy 在 python 中编写 L-BFGS 最小化函数时出错