Format currency in textfield in Swift on input

前端 未结 7 1816
一生所求
一生所求 2021-02-08 07:52

I am trying to format currency input in a textfield in Swift as the user inputs it.

So far, I can only format it successfully when the user finishes inputting:



        
7条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-08 08:44

    This worked for me: Naming of the variables need to be improved though. Multiplying by 10 was easy but figuring out how to divide by 10 and round down was tricky with the pointers.

        let numberFormatter = NumberFormatter()
        numberFormatter.numberStyle = .currency
    
    
        func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if textField == amountTextField {
            guard let text = textField.text else {return true}
    
            let oldDigits = numberFormatter.number(from: text) ?? 0
            var digits = oldDigits.decimalValue
    
            if let digit = Decimal(string: string) {
                let newDigits: Decimal = digit / 100
    
                digits *= 10
                digits += newDigits
            }
            if range.length == 1 {
                digits /= 10
                var result = Decimal(integerLiteral: 0)
                NSDecimalRound(&result, &digits, 2, Decimal.RoundingMode.down)
                digits = result
            }
    
            textField.text = NumberFormatter.localizedString(from: digits as NSDecimalNumber, number: .currency)
            return false
        } else {
            return true
        }
    }
    

提交回复
热议问题