[英]using String with UIStepper - Swift
i have a label and a UIStepper, i need to increase the number of that label without lossing the letters ( Kd ).我有一个 label 和一个 UIStepper,我需要在不丢失字母 (Kd) 的情况下增加 label 的数量。 my label will be like this "5.000 Kd" and when i increase the number i don't want to loss the ( Kd ) label.
我的 label 将是这样的“5.000 Kd”,当我增加数量时,我不想丢失(Kd)label。
this is my code这是我的代码
import UIKit
import GMStepper
class ViewController: UIViewController {
@IBOutlet var stepper: GMStepper!
@IBOutlet var price: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func stepper(_ sender: Any) {
let label = "5.000 Kd" as NSString
price.text! = String(label.doubleValue * stepper.value)
}
}
If you are hard-coding the string contents of the label, just maintain a numeric value and rebuild the label contents each time that value changes:如果您对 label 的字符串内容进行硬编码,只需维护一个数值并在每次该值更改时重建 label 内容:
class ViewController: UIViewController {
@IBOutlet var stepper: GMStepper!
@IBOutlet var priceLabel: UILabel!
var price: Double = 5.0
@IBAction func stepper(_ sender: Any) {
let newValue = price * stepper.value
//Format the price with 3 decimal places
let priceString = String(format: "%.3f", newValue)
Construct a string with the formatted price and " Kd" and put it in the label
priceLabel.text = "\(priceString) Kd")
}
}
Consider using NumberFormatter to format currency:考虑使用 NumberFormatter 来格式化货币:
let cf = NumberFormatter()
cf.currencyCode = "KWD"
cf.numberStyle = .currency
cf.string(from: 5000)
That respects the user's Locale.这尊重用户的语言环境。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.