Format currency in textfield in Swift on input

前端 未结 7 1964
一生所求
一生所求 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条回答
  •  旧时难觅i
    2021-02-08 08:41

    Based on @Robert answer. Updated for Swift 2.0

    //Textfield delegates
    func textField(textField: UITextField, shouldChangeCharactersInRange 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(currentString)
        default:
            if string.characters.count == 0 && currentString.characters.count != 0 {
                currentString = String(currentString.characters.dropLast())
                formatCurrency(currentString)
            }
        }
        return false
    }
    
    func formatCurrency(string: String) {
        print("format \(string)")
        let formatter = NSNumberFormatter()
        formatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle
        formatter.locale = NSLocale(localeIdentifier: "en_US")
        let numberFromField = (NSString(string: currentString).doubleValue)/100
        self.amountField.text = formatter.stringFromNumber(numberFromField)
        print(self.amountField.text )
    }
    

提交回复
热议问题