如何使用 UITableViewCell 的委托方法在标签中设置计算?
How do I set calculations in labels using a delegate method from 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 的标签中
我尝试设置我的代码类似于下面link中的代码
我已经尝试与代表传递数据。还有其他更好的方法吗?
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
}
}
- 将您的 UILabel 作为子视图添加到 UItableviewcell 容器视图中。
- 添加尾随、前导、顶部、底部约束。
- 设置UILabel行数0。
为动态高度添加重写 heightForRowAt 方法。
override func tableView(_ tableView: UITableView, heightForRowAt
indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
首先我想告诉你一切都按照你的要求做了。您只需在 class 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))"
}
}
}
我正在设置 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 的标签中
我尝试设置我的代码类似于下面link中的代码
我已经尝试与代表传递数据。还有其他更好的方法吗?
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
}
}
- 将您的 UILabel 作为子视图添加到 UItableviewcell 容器视图中。
- 添加尾随、前导、顶部、底部约束。
- 设置UILabel行数0。
为动态高度添加重写 heightForRowAt 方法。
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableViewAutomaticDimension }
首先我想告诉你一切都按照你的要求做了。您只需在 class 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))"
}
}
}