首页 > 解决方案 > 如何使用 UITableViewCell 中的委托方法在标签中设置计算?

问题描述

我正在设置一个 CartViewController 和一个 PopUpFeesController。

在 CartVC 中,我有一个单元格在 CartFooter cartTotal 标签内加起来,代表小计。同样在这里,我有 3 个标签,它们代表 PopUpFeesController 中小计、salesTax 和总计的转换。

在 CartFooter 中,我拥有所有的出口,并有一个代表与 CartVC 进行通信。popupFeesBtn

在 PopupFeesController 中,我有 3 个 UILabel(sTotal、stax 和 oaTotal)。当我按下 popupFeesBtn(在 CartFooter 中)时,我想在 PopupFeesController 中设置具有正确值的标签以在标签中显示转换。

由于无法将 cartTotal 转换为 PopupFeesController 中的标签,我如何需要使用该委托方法设置 UILabel(cartTotal)?

我如何能够获取从 CartVC CartFooter Cell cartFooter 标签传递到 PopUpFeesViewController 的小计,以便它可以从小计中计算税款和总计,并将它们显示在 PopUpFeesViewController 的标签中

我试图设置我的代码类似于下面链接中的代码

如何使用 UITableViewCell 中的委托方法设置 UISlider

我已经尝试与代表一起传递数据。还有其他更好的方法吗?


import UIKit

class CartViewController: UIViewController {

    var selectedFood: FoodList!       // allows data to be passed into the CartVC

    var cartValue : Float  = 0.0

    // allows data to be sepearted into sections
    var cartItems: [CartItem] = []
    var groupedCartItems: [String: [CartItem]] = [:]
    var storeSectionTitle: [String] = []

    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.

    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "AdditionalCosts" {
        let vc: PopupFeesController = segue.destination as! PopupFeesController
            vc.calculateFeesDelegate = self
        }
    }
}
extension CartViewController: UITableViewDelegate, UITableViewDataSource{

    func numberOfSections(in tableView: UITableView) -> Int {
        return storeSectionTitle.count
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let store = storeSectionTitle[section]
    return groupedCartItems[store]!.count
}

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cartCell = tableView.dequeueReusableCell(withIdentifier: "CartCell") as! CartCell

        let store = storeSectionTitle[indexPath.section]
        let cartItemsToDisplay = groupedCartItems[store]![indexPath.row]
        cartCell.configure(withCartItems: cartItemsToDisplay.foodList)

        return cartCell
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let cartHeader = tableView.dequeueReusableCell(withIdentifier: "CartHeader") as! CartHeader

        let headerTitle = storeSectionTitle[section]
        cartHeader.storeName.text = "\(headerTitle)"

        return cartHeader
    }

    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let cartFooter = tableView.dequeueReusableCell(withIdentifier: "CartFooter") as! CartFooter

        //Cell Total Code
        let store = storeSectionTitle[section]
        let arrAllItems = groupedCartItems[store]!
        var subtotal: Float = 0
        for item in arrAllItems {
            if item.productList.selectedOption == 1 {
                subtotal = subtotal + (Float(item.foodList.price) * Float(item.foodList.count))
            }
        }

        let numberFormatter = NumberFormatter()
        numberFormatter.numberStyle = .currency
        let total = numberFormatter.string(from: NSNumber(value: Float(subtotal)))
        subtotal = cartValue

        cartFooter.cartTotal.text = String(total!)
        cartFooter.additionalCostsDelegate = self

        return cartFooter
    }    
}

extension CartViewController: AdditionalCostsDelegate {
    func onTouchAdditionalCostsInfo(info: Float?) {
        let popUp = self.storyboard?.instantiateViewController(withIdentifier: "AdditionalCostsVC") as! PopUpViewController
        print("Subtotal: \(cartValue)")
        cartValue = Float(info ?? 0.00)

        self.present(popUp, animated: true) {
            popUp.subtotalLbl.text = "\(String(describing: info))"
        }
    }
}

extension CartViewController: CalculateFeesDelegate {
    func calculateFees(_ stotal: UILabel, _ sTax: UILabel, _ oaTotal: UILabel) {

        let subtotal = cartValue
        let tax = subtotal * Float(0.0825)
        let total = subtotal + tax

        let numberFormatter = NumberFormatter()
        numberFormatter.numberStyle = .currency
        let total = numberFormatter.string(from: NSNumber(value: Float(subtotal)))
        let salesTax = numberFormatter.string(from: NSNumber(value: Float(tax)))
        let overallTotal = numberFormatter.string(from: NSNumber(value: Float(total)))

        stotal.text = "\(String(describing: total))"
        sTax.text = "\(String(describing: marijuanaTax))"
        oaTotal.text = "\(String(describing: overallTotal))"
    }    
}

protocol AdditionalCostsDelegate: class {
    func onTouchAdditionalCostsInfo(info: Float?)
}

class CartFooter: UITableViewCell {

    var additionalCostsDelegate: AdditionalCostsDelegate? = nil

    @IBOutlet weak var cartTotal: UILabel!

    @IBOutlet weak var popupFeesBtn: UIButton!

    @IBAction func popFeesOnClicked(_ sender: Any) {
        sendData2PopupFees()
    }

    func sendData2PopupFees(){
        self.additionalCostsDelegate?.onTouchAdditionalCostsInfo(info: Float(cartTotal?.text! ?? "0.0"))
    }
}

protocol CalculateFeesDelegate {
    func calculateFees(_ stotal: UILabel, _ sTax: UILabel, _ oaTotal: UILabel)
}

class PopupFeesController: UIViewController {

    @IBOutlet weak var subtotalLbl: UILabel!
    @IBOutlet weak var salesTaxLbl: UILabel!
    @IBOutlet weak var overallTotalLbl: UILabel!

    var calculateFeesDelegate: CalculateFeesDelegate?

    override func viewDidLoad() {
        super.viewDidLoad()

        let subtotal = Float(subtotalLbl.text!)

        let tax = Float((subtotal) * 0.0825) // getting an error here when pressing popupFeesBtn => Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
        let total = Float((subtotal) + salesTax)
        let numberFormatter = NumberFormatter()
        numberFormatter.numberStyle = .currency
        let sTotal = numberFormatter.string(from: NSNumber(value: Float(subtotal!)))
        let salesTax = numberFormatter.string(from: NSNumber(value: Float(tax)))
        let overallTotal = numberFormatter.string(from: NSNumber(value: Float(total)))

        subtotalLbl.text = "\(subTotal)"
        salesTaxLbl.text = "\(salesTax)"
        overallTotalLbl.text = "\(total)"
    }

    @IBAction func returnButton(_ sender: Any) {
        dismiss(animated: true, completion: nil)
    }

}

class CartItem {
    var foodList: FoodList!

    init(foodList: FoodList) {

        foodList = foodList
    }
}

标签: iosswiftdelegatestableview

解决方案


首先我想告诉你,一切都按照你的要求做了。您只需在类PopupFeesController中创建一个 Float 类型的变量。您必须将此方法“onTouchAdditionalCostsInfo”中的值传递给 PopupFeesController。

您必须用您的代码替换PopupFeesController代码和“ onTouchAdditionalCostsInfo ”,您的数据将从一个视图控制器传递到另一个视图控制器。

class PopupFeesController: UIViewController {

@IBOutlet weak var subtotalLbl: UILabel!
@IBOutlet weak var salesTaxLbl: UILabel!
@IBOutlet weak var overallTotalLbl: UILabel!

var calculateFeesDelegate: CalculateFeesDelegate?
var totalCartValue : Float  = 0.0

override func viewDidLoad() {
    super.viewDidLoad()

    print("\(totalCartValue)")
    let subtotal = Float(subtotalLbl.text!)

    let tax = Float((subtotal) * 0.0825) // getting an error here when pressing popupFeesBtn => Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
    let total = Float((subtotal) + salesTax)
    let numberFormatter = NumberFormatter()
    numberFormatter.numberStyle = .currency
    let sTotal = numberFormatter.string(from: NSNumber(value: Float(subtotal!)))
    let salesTax = numberFormatter.string(from: NSNumber(value: Float(tax)))
    let overallTotal = numberFormatter.string(from: NSNumber(value: Float(total)))

    subtotalLbl.text = "\(subTotal)"
    salesTaxLbl.text = "\(salesTax)"
    overallTotalLbl.text = "\(total)"
}

@IBAction func returnButton(_ sender: Any) {
    dismiss(animated: true, completion: nil)
}

}


extension CartViewController: AdditionalCostsDelegate {
  func onTouchAdditionalCostsInfo(info: Float?) {
    let popUp = self.storyboard?.instantiateViewController(withIdentifier: "AdditionalCostsVC") as! PopUpViewController
    popUp.totalCartValue = Float(info ?? 0.00)
    self.present(popUp, animated: true) {
        popUp.subtotalLbl.text = "\(String(describing: info))"
    }
  }
}

推荐阅读