【问题标题】:How to increase and decrease the label value (price) according to Plus Minus button count in swift如何在swift中根据加减按钮计数增加和减少标签值(价格)
【发布时间】:2021-08-13 15:58:41
【问题描述】:

我从下面的 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
    }
}

请帮我做这件事

【问题讨论】:

  • 与 productCount 是用于跟踪计数的属性相同,您需要一个 Double 类型的属性来保存价格。如果您的 json 包含没有任何格式的纯数字,您应该可以使用 Double(discount_price)
  • @JoakimDanielson.. 当减少.. 然后

标签: json swift button label


【解决方案1】:

让我们看一下这个示例代码:

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 类型来处理递增和递减运算符。 要将数字分配回 String,我们可以使用以下扩展名:

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

希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-19
    • 2016-01-26
    • 2017-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多