如何计算表格视图中的值并显示在单独的标签中 [英] how to calculate the values in table view and to display in separate label

查看:25
本文介绍了如何计算表格视图中的值并显示在单独的标签中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表格视图项目列表.在每个单元格中,我都有产品名称、数量、价格.我需要计算每个单元格产品的数量 x 价格.我必须对所有单元格总数求和.并且必须显示在我单独的单元格中.如何做到这一点.

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;

我有一个名为 totallabel 的独立标签.请给我一些代码解释.关于如何计算每个单元格并将所有总价相加.并在我的标签中显示总和.

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.

我试过了:

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

        }

但是我在 for 循环中崩溃了:

But i am getting crash on for loop that :

致命错误:无法形成带有 upperBound <的 Range下界

提前致谢!!

推荐答案

您可以在 numberOfRowsInSection 方法中计算总和.

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
}

这篇关于如何计算表格视图中的值并显示在单独的标签中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆