将tableView中的值添加到标签Swift4

时间:2018-06-14 10:56:14

标签: xcode swift4

我正在尝试将我添加到tableview的值添加到我的totalLabel。我已附上我的代码和下面的截图来帮助。在示例中,它不会添加到totalLabel。第1项加上第2项应该是2美元,假设我为5美元添加另一项,那么它将是7美元。

 import UIKit
 import AVFoundation

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {


@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var totalLabel: UILabel!


var items: [Item] = []

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

}

@IBAction func addItem(_ sender: Any) {

    let alert = UIAlertController(title: "Add Item", message: "Add item And Price", preferredStyle: .alert)
    alert.addTextField { (UITextField) in
        UITextField.placeholder = "Enter Item Name"
    }
    alert.addTextField { (UITextField) in
        UITextField.placeholder = "Enter Item Price"
        UITextField.keyboardType = .numbersAndPunctuation
    }
    alert.addAction(UIAlertAction(title: "Add", style: .default, handler: { (UIAlertAction) in
        let content = alert.textFields![0] as UITextField
        let content2 = alert.textFields![1] as UITextField
        let value = "\(content2.text!)"

        let item = Item(itemName: "\(content.text!)", itemPrice: Double(value)!)


        self.items.append(item)

        self.tableView.reloadData()

        guard let total = Double(self.totalLabel.text!) else { return }
        let sum = String(total + Double(value)!)
        self.totalLabel.text = sum


    }))
    alert.addAction(UIAlertAction(title: "Cancel", style: .destructive, handler: nil))

    self.present(alert, animated: true, completion: nil)

}


func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return items.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    let items = self.items[indexPath.row]
    cell.textLabel?.text = items.itemName
    cell.detailTextLabel?.text = "$\(String(items.itemPrice))"

    var totalAmount = 0.0
    for value in self.items {
        totalAmount = totalAmount + items.itemPrice

        print(value)
        print(totalAmount)

    }

    totalLabel.text = "Total is $\(totalAmount)"
    return cell
}

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return "Grocery List"
}

}

enter image description here

enter image description here

3 个答案:

答案 0 :(得分:2)

只需将此for循环替换为cellForRowAt中的现有循环

    for value in self.items {
        totalAmount = totalAmount + value.itemPrice
    }

答案 1 :(得分:1)

正如我在回复您previous question时已经提到的那样,您必须总结price数组中的items

创建一个重新加载表格视图的功能更新total标签

func reloadAll() {
   tableView.reloadData()
   let totalAmount = String(items.map{$0.itemPrice}.reduce(0.0, +))
   totalLabel.text = "Total is $\(totalAmount)"
}

然后将此方法称为无处不在,您可以调用tableView.reloadData(),例如在警报操作中替换这些行

self.tableView.reloadData()

guard let total = Double(self.totalLabel.text!) else { return }
let sum = String(total + Double(value)!)
self.totalLabel.text = sum

只需

self.reloadAll()

并删除cellForRow中的以下行。更新此方法中的标签是没有意义的,因为执行相同的计算items.count次(循环运行items.count²次!)

var totalAmount = 0.0
for value in self.items {
    totalAmount = totalAmount + items.itemPrice

    print(value)
    print(totalAmount)

}

totalLabel.text = "Total is $\(totalAmount)"

答案 2 :(得分:0)

更新此方法

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    let items = self.items[indexPath.row]
    cell.textLabel?.text = items.itemName
    cell.detailTextLabel?.text = "$\(String(items.itemPrice))"

    var totalAmount = 0.0
    for value in self.items {
      totalAmount = totalAmount + items.itemPrice
    }

    totalLabel.text = "Total is $\(totalAmount)"
    return cell
}

我希望这就是你所期待的。