mack mack - 1 year ago 84
iOS Question

how to calculate the values in table view and to display in separate label

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
. 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 !!

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download