【问题标题】:(SWIFT 4) How to calculate sum of the columns indexpath.row in the tableview?(SWIFT 4)如何计算 tableview 中列 indexpath.row 的总和?
【发布时间】:2018-11-09 15:33:46
【问题描述】:

如何计算不同单元格中相同列的总和,而不是同一单元格中的总和。

不知道怎么解决。

import UIKit

class ResultViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate {

    @IBOutlet var tableview: UITableView!
    @IBAction func backPage(_ sender: Any) {
        self.presentingViewController?.dismiss(animated: true)
    }

    let ad2 = UIApplication.shared.delegate as? AppDelegate

    @IBAction func resetHist(_ sender: Any) {
        ad2?.listPrice = [String]()
        ad2?.listAmt = [String]()

        tableview.reloadData()
    }

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

        return ad2?.listPrice.count ?? 0
    }

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

        cell.resultPrice?.text = ad2?.listPrice[indexPath.row]
        cell.resultAmt?.text = ad2?.listAmt[indexPath.row]

        var sum = 0

        // how to calculate sum of the same columns in different cells
        for i in ad2?.listPrice.count {

            sum += Int(ad2?.listPrice[i])

        }

        return cell
    }
}

【问题讨论】:

  • 你能举个例子吗?不太明白这里的列是什么意思。 (不确定您是否理解列的含义,无意冒犯)
  • 对不起。我英语不成熟。 column 表示 tableviewcell 的每个元素 ex) listPrice[0], listPrice[1], ...
  • 你打算在cellForRowAt中使用它做什么?

标签: ios swift uitableview indexpath


【解决方案1】:

如果您想以尝试的方式枚举元素:

var sum = 0
for pair in listPrice.enumerated() {
    sum += Int(pair.element) //listPrice[pair.index]
}

或者直接使用这个:

let sum = ad2?.listPrice.compactMap(Int.init).reduce(0, +)

【讨论】:

    【解决方案2】:

    使用compactMapString 数组映射到Intreduce 以总结项目。

    let ad2 = UIApplication.shared.delegate as! AppDelegate
    
    ...
    
    let sum = ad2.listPrice.compactMap(Int.init).reduce(0, +)
    

    cellForRow 是错误的代码位置。

    注意事项:

    • 基本上不使用多个数组作为数据源。
    • 如果listPrice 包含数值,请使用更合适的类型,例如IntDouble
    • 不要将AppDelegate 用作存储数据的常用位置。
    • 如果AppDelegate 不存在,则应用甚至不会启动,因此强制施放它是绝对安全的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-03
      • 1970-01-01
      • 2018-10-03
      • 2021-07-31
      • 2013-03-21
      • 1970-01-01
      • 2023-03-25
      • 2013-05-26
      相关资源
      最近更新 更多