swift中如何根据Plus Minus按钮数增加和减少标签值(价格)

How to increase and decrease the label value (price) according to Plus Minus button count in swift

我从 JSON 获取价格,如下所示并显示在屏幕上,效果很好

func populatePage() {

let detailsData = detailsDB?.result?.product?.product_details
price = detailsData?.price ?? ""
discountPrice = detailsData?.discount_price ?? ""

self.lblDiscountPrice.text = discountPrice != "0.000" && compareDate(fromDate: detailsData?.from_date ?? "", toDate: detailsData?.to_date ?? "") ? "\(discountPrice) KWD" : "\(price) KWD"
self.lblRealPrice.text = discountPrice != "0.000" && compareDate(fromDate: detailsData?.from_date ?? "", toDate: detailsData?.to_date ?? "") ? "\(price) KWD" : ""
self.lblLine.isHidden = discountPrice != "0.000" && compareDate(fromDate: detailsData?.from_date ?? "", toDate: detailsData?.to_date ?? "") ? false : true
 }

我需要按增减算价格也增减,如何?

 @IBAction func increment(_ sender: UIButton) {
    self.productCount += 1
    
    self.lblProductCount.text = productCount.description
    
}
@IBAction func decrement(_ sender: UIButton) {
    if self.productCount >= 2 {
        self.productCount -= 1
        self.lblProductCount.text = self.productCount.description
    }
}

请帮我做这个

我们来看看这个示例代码:

private var itemQuantity: Int = 1 //By Defaults: 1

@IBAction func onTapDecreaseQuantity(_ sender: Any) {
    updateItemQuantity(isIncreasing: false)
}

@IBAction func onTapIncreaseQuantity(_ sender: Any) {
    updateItemQuantity(isIncreasing: true)
}

private func updateItemQuantity(isIncreasing: Bool) {
    guard let price = item?.itemPrice else { return }
    itemQuantity = isIncreasing ? itemQuantity + 1: itemQuantity - 1
    itemQuantityLabel.text = String(itemQuantity)
    itemPriceLabel.text = "Price: $\((price * Float(itemQuantity)).toString(fractionDigits: 2))"
    minusItemNumberButton.isEnabled = itemQuantity > 1
}

无论是双精度还是浮点数,您都需要通过类型转换将字符串解析为数字。我正在使用本地 var Int 类型来处理递增和递减运算符。 要将数字分配回字符串,我们可以使用以下扩展名:

extension Float {
    func toString(fractionDigits: Int) -> String {
        let formatter = NumberFormatter()
        formatter.minimumFractionDigits = fractionDigits
        formatter.maximumFractionDigits = fractionDigits
        return formatter.string(from: NSNumber(value: self)) ?? "\(self)"
    }
}

希望对您有所帮助。