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

时间:2017-08-26 02:53:01

标签: swift function uitableview sum cell

我无法理解这一点,因为我对表格单元格知之甚少。我正在为自己构建发票应用程序。在我的tableview自定义单元格中,我在右侧制作了一个标签,用于到期金额。当您填写发票时,它会打印出该标签中的金额。

我在最顶层调用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.
    }


}

第二个控制器

@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)
        }

    }

2 个答案:

答案 0 :(得分:1)

不要计算cellForRowAt中的总数。每次在屏幕上显示行时都会调用它,所以即使它是对所有内容进行求和,也会出错。创建一个单独的函数来计算总和并返回填充标签的函数。类似的东西:

func calculateSum() {
    var sum = 0

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

    totalDue.text = "\(sum)"
}

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

答案 1 :(得分:0)

请添加此

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

从viewcontroller中的其他位置删除sum

然后在你的第二个视图控制器

amountDue.append(amountInput.text!)

之后

添加此

sum += Double(amountInput.text!)!

然后在ViewController

添加此

override func viewDidAppear(_ animated: Bool) {
                super.viewDidAppear(animated)
                totalDue.text = "\(sum)"
}