簡體   English   中英

(SWIFT 4) 如何計算 tableview 中列 indexpath.row 的總和?

[英](SWIFT 4) How to calculate sum of the columns indexpath.row in the tableview?

如何計算不同單元格中相同列的總和,而不是同一單元格中的總和。

我不知道如何解決。

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
    }
}

使用compactMapString數組映射到Int並使用reduce來總結項目。

let ad2 = UIApplication.shared.delegate as! AppDelegate

...

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

cellForRow是代碼的錯誤位置。

注意事項:

  • 基本上不要使用多個數組作為數據源。
  • 如果listPrice無論如何listPrice包含數值,請使用更合適的類型,如IntDouble
  • 不要將AppDelegate用作存儲數據的常用位置。
  • 如果AppDelegate不存在,該應用程序甚至不會啟動,因此強制轉換它是完全安全的。

如果您想按照您嘗試的方式枚舉元素:

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

或者只是使用這個:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM