-2

同じセルの合計ではなく、異なるセルの同じ列の合計を計算する方法。

解決方法がわかりません。

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

2 に答える 2

0

配列compactMapをマップし、アイテムを合計するために使用します。StringIntreduce

let ad2 = UIApplication.shared.delegate as! AppDelegate

...

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

コードのcellForRow場所が間違っています。

ノート :

  • 基本的に、複数の配列をデータ ソースとして使用しないでください。
  • listPriceとにかく数値が含まれている場合は、 Intorのようなより適切な型を使用してくださいDouble
  • AppDelegateデータを保存する一般的な場所として使用しないでください。
  • AppDelegate存在しない場合、アプリは起動さえしないので、強制的にキャストしても完全に安全です。
于 2018-11-09T16:08:58.077 に答える