swift - 在 Swift 中添加表格单元格中的标签总和

标签 swift function uitableview sum cell

我无法弄清楚这一点,因为我对表格单元格了解不够。我正在为自己构建一个发票应用程序。在我的表格 View 自定义单元格中,我在右侧制作了一个标签,用于显示应付金额。当您填写发票时,它会打印出该标签中的金额。

我在最上面的调用 totalDue 处有一个空标签,我想得到表中每个金额的总和。我正在为此苦苦挣扎。

我有的是

import UIKit

var clientName = [String]()
var dueDate = [String]()
var projecDescript = [String]()
var dateStamp = Date()
var invoiceNum = [String]()
var amountDue = [String]()

var clientPicker = [""]





// Custom cell to make all input fields custom
class CustomCell: UITableViewCell {
    //Make your outlets here, connect the outlets from cell in your storyboard

    @IBOutlet var clientNameLabel: UILabel!
    @IBOutlet var descriptionLabel: UILabel!
    @IBOutlet var dateLabel: UILabel!
    @IBOutlet var amountLabel: UILabel!
    @IBOutlet var invoiceNum: UILabel!
    @IBOutlet var dateStamp: UILabel!

}

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet var clientTableList: UITableView!
    @IBOutlet var totalDue: UILabel!
    @IBOutlet var totalBillsLabel: UILabel!


    func calculateSum() {
    var sum = 0

    for amount in amountDue {
    sum += amount
    }

    totalDue.text = "\(sum)"

    }


    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return (clientName.count)
        return (dueDate.count)
        return (projecDescript.count)
        return (invoiceNum.count)
        return (amountDue.count)

    }



    // This is the new items added into the inputs
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let cell = tableView.dequeueReusableCell(withIdentifier: "clientCell", for: indexPath) as! CustomCell

        // Adds Clients Name
        let companyName = clientName[indexPath.row]
        cell.clientNameLabel?.text = companyName

        // Adds Clients Description
        let descriptionName = projecDescript[indexPath.row]
        cell.descriptionLabel?.text = descriptionName

        // Adds the amount due
        let amountName = amountDue[indexPath.row]
        cell.amountLabel?.text = "$\(amountName)"

        //Adds the total number of bills that you have in invoice
        totalBillsLabel.text = "\(indexPath.row + 1)"

        //Adding sum of all bills
        sum += Int((amountName as NSString).floatValue)
        //sum = Int((amountName as NSString).floatValue)

        totalDue.text = "\(sum)"

        //Adds DueDate
        let invoiceDate = "Due \(dueDate[indexPath.row])"
        cell.dateLabel?.text = invoiceDate

        //Adds invoice Number
        let invoiceNum = "Invoice #BMCS \(indexPath.row + 1)"
        cell.invoiceNum.text = invoiceNum

        //TimeStamp in the label datestamp
        let timeStamp = "\(DateFormatter.localizedString(from: Date(), dateStyle: .short, timeStyle: .short))"
        cell.dateStamp?.text = timeStamp

        return cell
    }


    func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
        let editAction = UITableViewRowAction(style: .default, title: "Edit") { (action, index) in

            //tableView.isEditing = true


            DispatchQueue.main.async() {
                self.performSegue(withIdentifier: "EditDetails", sender: self)
            }


            print("Edit Button Pressed")
        }

        editAction.backgroundColor = UIColor.green

        let deleteAction = UITableViewRowAction(style: .destructive, title: "Remove") { (action, indexPath) in
            //Remove the labels in the custom cell
            clientName.remove(at: indexPath.row)
            //dueDate.remove(at: indexPath.row)
            projecDescript.remove(at: indexPath.row)

            amountDue.remove(at: indexPath.row)
            tableView.deleteRows(at: [indexPath], with: .fade)

            //minus one total bill when deleting one
            self.totalBillsLabel.text = "\(indexPath.row - 1)"
            if indexPath.row == 0 {
                self.totalBillsLabel.text = "0"
            }



            self.clientTableList.reloadData()

        }

        let emailAction = UITableViewRowAction(style: .default, title: "Email") { (action, index) in
            print("Email Button Pressed")
        }

        emailAction.backgroundColor = UIColor.orange

        let phoneCallAction = UITableViewRowAction(style: .default, title: "Call") { (action, index) in
            print("Call Button Pressed")
        }

        phoneCallAction.backgroundColor = UIColor.blue



        return [deleteAction,editAction,emailAction,phoneCallAction]
    }

    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }


    override func viewDidAppear(_ animated: Bool) {
        clientTableList.reloadData()

    }




    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

第二 Controller

@IBAction func addInvoice(_ sender: Any) {


        if clientNameInput.text != "" && descriptionNameInput.text != ""  && amountInput.text != ""
        {
            clientName.append(clientNameInput.text!)
            //clientInput.text = ""

            projecDescript.append(descriptionNameInput.text!)
            //descriptionFieldInput.text = ""

            //dueDate.append(dateInput.text!)
            //dateInput.text = ""

            amountDue.append(amountInput.text!)
            //amountList.text = ""

            dueDate.append(newDueDateLabel.text!)


            // After hit send this is the button that takes you back without having to back out yourself
            _ = navigationController?.popViewController(animated: true)
        }

    }

最佳答案

不要在 cellForRowAt 中计算总数。每次该行在屏幕上可见时都会调用它,因此即使它对所有内容求和,也是错误的。创建一个单独的函数来计算总和并将其返回以填充标签。像这样的东西:

func calculateSum() {
    var sum = 0

    for amount in amountDue {
        sum+= Int(amount) // more practical to convert to float here
    }

    totalDue.text = "\(sum)"
}

然后在您的 viewDidLoad 和其他适当的地方调用此方法,例如在添加新行之后。

关于swift - 在 Swift 中添加表格单元格中的标签总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45891494/

相关文章:

ios - 可选的意外发现 nil 和崩溃日志信息

php - $provider = function() vs 函数provider()

ios - 每个唯一的重用标识符是否都有自己唯一的重用队列?

swift - 使用 UISwitch 显示/隐藏表格 View 单元格

ios - 时间分析器不显示功能

ios - iOS 14 中 UIDocumentPickerViewController 的初始化

c - 为什么返回 struct 属性的 C 函数在第一次循环迭代后返回 0?

ios - 由于未捕获的异常 'NSInternalInconsistencyException' 而终止应用程序

ios - 如何向从 nib 文件加载的 subview 添加约束?

php - 使用自定义函数而不包含它们