计算tableView中每个单元格的值

问题描述 投票:0回答:1

我正在尝试从每个tableViews单元格中获取总数,然后添加到总标签。由于每个单元格可能有不同的数量和价格,我使用Arrays数量和产品基价。

我已经按照这个问题/答案,但看着问的人正在使用结构:how to calculate the values in table view and to display in separate label

var total = 0.0
var basePriceArray = [2.45, 18.95, 3.8]
var quantityArray = [2.0, 1.0, 5.0]

cellForRowAt

let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath) as! BasketCell
let basePriceAtIndex = basePriceArray[indexPath.row]
let quantityAtIndex = quantityArray[indexPath.row]
let priceAtIndex = basePriceAtIndex * quantityAtIndex
//When I add the priceAtIndex to the cell label it is calculating perfectly
//ie 4.9, 18.95, 19

//Below is my problem
for _ in productNameArray {
    total += priceAtIndex
}
print(total)

//The total is printing
  14.700000000000001 (ignore the one)
  71.55
  128.55

已经弄清楚它背后的逻辑,它将priceAtIndex乘以productNameArray中有多少产品(因为for-in循环计算有多少产品)。然后将最后一个价格添加到下一个价格即

4.9 x 3 = 14.7

18.95 x 3 = 56.85 + 14.7 = 71.55

19.00 x 3 = 57 + 56.85 + 14.7 = 128.55

我理解它背后的逻辑,但由于某种原因无法弄清楚修复?

编辑1忘了提及我的productNameArray有3个产品因此x 3

ios iphone swift uitableview
1个回答
1
投票

我在数量和产品基价上都使用Arrays

不要那样做。使用包含数量和价格的结构以及产品的计算属性

struct Product {

    let name : String

    // many other properties 

    var quantity : Int
    var price : Double

    var priceTotal : Double {
        return Double(quantity) * price
    }
}

和数据源数组

var products = [Product]()

在cellForRow map产品到priceTotal并总结

let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath) as! BasketCell

let total = products.map{$0.priceTotal}.reduce(0.0, +)
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .decimal
numberFormatter.maximumFractionDigits = 2
cell.textLabel?.text = numberFormatter.string(from: NSNumber(value: total))

当然,如果Productquantity发生变化,你必须更新数据源的price实例。

© www.soinside.com 2019 - 2024. All rights reserved.