I'm trying to make my numbers (taken from custom button input) to move from right to left with two decimal places. I'm using 10 buttons (0-9) with sender tags attached to them for the buttonInput
and I want the right to left decimal number to appear in the labelText
label. I know you can use textfields to accomplish this, but I want to use my custom buttons.
Desired outcome: user taps 1 button, labelText
changes to $0.01; user taps 2 button, labelText
changes to $0.12; etc..
Xcode Version 12.1; Swift Version 5.3
Here's what I've got so far.. I'm new to Swift, so go easy on me!
@IBOutlet weak var labelText: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func numPad(_ sender: UIButton) {
//button number
let buttonInput = Double(sender.tag - 1)
//label text to number conversion
let labelValue = labelText.text
let intValue = Double(labelValue!)
//move number to the right of decimal
//let addedValue = (intValue! * 0.10) + buttonInput
let addedValue = intValue! + buttonInput
let numForm = NumberFormatter()
numForm.numberStyle = .decimal
//numForm.currencySymbol = "$"
numForm.minimumIntegerDigits = 0
numForm.maximumIntegerDigits = 4
numForm.maximumFractionDigits = 2
numForm.minimumFractionDigits = 2
labelText.text = numForm.string(for: addedValue)
}
All you need is to convert your button tag to Double, divide it by 100, and sum it to the current value of your label multiplied by 10:
let cents = Double(sender.tag - 1)/100
print("cents", cents)
let oldValue = (Double(labelText.text!) ?? .zero) * 10
print("oldValue", oldValue)
let newValue = oldValue + cents
print("newValue", newValue)
Note: You should never use your UI to hold values, only to display them. I would also use Decimal
instead of Double
to preserve its fractional digits precision:
var labelValue: Decimal = .zero
let cents = Decimal(sender.tag - 1)/100
print("cents", cents)
let newValue = labelValue * 10
print("newValue", newValue)
labelValue = newValue + cents
print("labelValue", labelValue)
let numForm = NumberFormatter()
numForm.numberStyle = .decimal
numForm.minimumIntegerDigits = 1
numForm.maximumIntegerDigits = 4
numForm.maximumFractionDigits = 2
numForm.minimumFractionDigits = 2
labelText.text = numForm.string(for: labelValue)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.