ios - 如何计算表格 View 中的值并显示在单独的标签中

标签 ios swift uitableview

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

我的表格 View 单元格代码将如下所示:

 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 .请给我一些代码解释。关于如何计算每个单元格并求和所有总价。并在我的标签中显示总金额。

我试过了:

 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 循环中崩溃了:

fatal error: Can't form Range with upperBound < lowerBound

提前致谢!!

最佳答案

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

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
}

关于ios - 如何计算表格 View 中的值并显示在单独的标签中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40504091/

相关文章:

ios - 为什么我可以在我的案例中访问单元测试类中的私有(private)方法

swift - 如何用两种不同颜色画一个空心圆?

swift - NSManagedObject 不是故障,但应用程序在后台线程上访问它时崩溃

iphone - UITableViewCell 缓存其 backgroundView 属性

iphone - UITableView 的 reloadRowsAtIndexPaths : (NSArray *) indexPaths failing to cause a reload unless you call it twice?

ios - 无法导入桥接头 facebook sdk

ios - xcode 6 升级导致 prepare for segue lag showing screen

ios - NSMutableDictionary setobject : forkey: crashes with unrecognised selector message

ios - Swift 关闭然后打开导致加载两次

iOS - 从容器内嵌入的 UITableView 检索父 View 中的单元格标题