Reputation: 611
I have a list of table view item. And in each cell I have the product name, qty, price. I need to calculate the each cell product qty x price. And I have to sum all the cell total. And have to display in my separate cell. How to do that.
My table view cell code will look like this :
let cell = tableView.dequeueReusableCell(withIdentifier: "cartcel", for: indexPath) as! cartTableViewCell
cell.productName.text = Addtocartdata[indexPath.row].cartproName
cell.productQty.text = Addtocartdata[indexPath.row].cartproPrice
cell.productAmount.text = Addtocartdata[indexPath.row].cartproPrice
return cell;
I have one separate label called totallabel
. Please give me some code explain. On how to do the calculation of each cell and to sum all the total price. And to display the total sum in my label.
I tried :
var total11 : Double = 0.0
let totalitem : Int = self.Addtocartdata.count as Int
for item in 0...totalitem - 1 {
let subtotal = 0.0
total11 = subtotal + Double(self.Addtocartdata[item].cartproPrice!)!
}
But i am getting crash on for loop that :
fatal error: Can't form Range with upperBound < lowerBound
Thanks in advance !!
Upvotes: 0
Views: 3346
Reputation: 2496
You can calculate the sum in numberOfRowsInSection
method.
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let sum = 0.0
for item in AddToCart {
sum += Double(item.cartproPrice) * Double(item.cartproQty)
}
label.text = "\(sum)"
return AddToCart.count
}
Upvotes: 2