Format currency in textfield in Swift on input

前端 未结 7 1787
一生所求
一生所求 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

    Swift 5

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { // return NO to not change text
    
        switch string {
        case "0","1","2","3","4","5","6","7","8","9":
            currentString += string
            formatCurrency(string: currentString)
        default:
            if string.count == 0 && currentString.count != 0 {
                currentString = String(currentString.dropLast())
                formatCurrency(string: currentString)
            }
        }
        return false
    }
    
    func formatCurrency(string: String) {
        print("format \(string)")
        let formatter = NumberFormatter()
        formatter.numberStyle = NumberFormatter.Style.currency
        formatter.locale = NSLocale(localeIdentifier: "en_US") as Locale
        let numberFromField = (NSString(string: currentString).doubleValue)/100
        //replace billTextField with your text field name
        self.billTextField.text = formatter.string(from: NSNumber(value: numberFromField))
        print(self.billTextField.text ?? "" )
    }
    

提交回复
热议问题