1

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)
}
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571

1 Answers1

0

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)
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
  • Do you have any idea how to implement a backspace button with this code? – Chris Bookmyer Nov 16 '20 at 22:44
  • @ChrisBookmyer you need to subclass `UITextField` and override `deleteBackward` method. For a localized currency textfield implementation you can check this post https://stackoverflow.com/a/29783546/2303865 – Leo Dabus Nov 16 '20 at 23:09