How to input currency format on a text field (from right to left) using Swift?

前端 未结 9 1023
甜味超标
甜味超标 2020-11-22 01:57

I have a number let’s say 0.00.

  • When the user taps 1. We should have 0.01
  • When the user taps 2. We should display 0.
9条回答
  •  孤街浪徒
    2020-11-22 02:27

    After a lot of trial and error with the suggested answers, I found a pretty straight forward solution:

    The setup for the textField needs to be called in your view's setup.

    In the switch statement, if the user puts in a number between 0 and 9, the number is added to the previous string value. The default case covers the backspace button and removes the last character from the string.

    The locale for the numberFormatter is set to current, so it works with different currencies.

    func setupTextField() {
            textField.delegate = self
            textField.tintColor = .clear
            textField.keyboardType = .numberPad
    }
    
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        setFormattedAmount(string)
        
        return false
    }
    
    private func setFormattedAmount(_ string: String) {
        switch string {
        case "0", "1", "2", "3", "4", "5", "6", "7", "8", "9":
            amountString = amountString + string
        default:
            if amountString.count > 0 {
                amountString.removeLast()
            }
        }
        
        let amount = (NSString(string: amountString).doubleValue) / 100
        textField.text = formatAmount(amount)
    }
    
    private func formatAmount(_ amount: Double) -> String {
        let formatter = NumberFormatter()
        formatter.numberStyle = .currency
        formatter.locale = .current
        
        if let amount = formatter.string(from: NSNumber(value: amount)) {
            return amount
        }
        
        return ""
    }
    

提交回复
热议问题