获取单元格中的值的总和

时间:2018-05-26 22:31:20

标签: ios swift

我有一个跟踪酒店收据的表格视图(每次用户输入酒店的日期,费用和名称时,点击添加按钮,它会在表格中添加一行新信息。

我在表格下面有两个文本字段,我想显示总条目(行数)和成本字段的总和。问题是我无法弄清楚如何做到这一点,或者甚至是否可能。

我发现了一些关于它的帖子,但它们似乎都有一定数量的行。

extension HotelViewController: UITableViewDataSource {

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

    let numberOfSections = frc.sections?.count
    return numberOfSections!

}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    let numberOfRows = frc.sections?[section].numberOfObjects
    return numberOfRows!

}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "HotelCell", for: indexPath) as! HotelTableViewCell
    let item = frc.object(at: indexPath) as! DriveAwayHotel

    cell.date.text = item.date
    cell.name.text = item.name
    cell.cost.text = "$\(item.cost ?? 0.00)"

    return cell

}

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {

    let managedObject : NSManagedObject = frc.object(at: indexPath) as! NSManagedObject
    pc.delete(managedObject)

    do {

        try pc.save()

    } catch {

        print(error)
        return

    }

}

Hotel receipt view controller

1 个答案:

答案 0 :(得分:2)

你不应该尝试对你的细胞进行数学运算。你应该对你的模型进行数学计算。

您是要尝试汇总表格中的所有条目,还是只查看可见的单元格?

如果要对表视图中的所有条目求和,则循环遍历frc.sections数组中的所有部分,遍历每个部分中的所有条目,并将它们全部添加。 (该代码很容易编写。)

如果您只想对当前可见单元格的条目求和,请调用表格视图的indexPathsForVisibleRows方法以获取可见单元格的indexPaths数组,循环遍历这些indexPaths,获取每个部分和行的条目,并将那些添加到一起。 (该代码也很容易编写。)

编辑:

汇总所有参赛作品的代码可能类似于下面的内容(因为我不知道您的数据模型,我不得不猜测一下)

var total = 0.0
guard let sections = frc.sections?.count else { return }
for section in 0..<sections {
  guard let rows = frc.sections?[section].numberOfObjects else { continue }
  for row in 0..<rows {
    let indexPath = IndexPath(row: row, section: section)
    let item = frc.object(at: indexPath) as! DriveAwayHotel
    total += item.cost
  }
}