Format a UITextField for currency

前端 未结 2 674
梦谈多话
梦谈多话 2021-01-16 10:34

I have a UITextField on my aplication that receives only numeric input from the user. This numeric input represents currency and have the default value of 0.00.

I wo

2条回答
  •  [愿得一人]
    2021-01-16 11:33

    Implement UITextFieldDelegate and add next methods:

    Swift:

    let currencySign = "$"
    
    // Adds $ before the text, e.g. "1" -> "$1" and allows "." and ","
    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool
        {
        var value = textField.text
    
        var newString = (textField.text as NSString).stringByReplacingCharactersInRange(range, withString: string)
        var components = newString.componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: "1234567890,.").invertedSet)
    
        var decimalString = "".join(components) as NSString
        var length = decimalString.length
    
        if length > 0 {
            value = "\(currencySign)\(decimalString)"
        }
        else {
            value = ""
        }
        textField.text = value
    }
    
    // Formats final value using current locale, e.g. "130,50" -> "$130", "120.70" -> "$120.70", "5" -> "$5.00"
    func textFieldDidEndEditing(textField: UITextField) {
            var value = textField.text
            var components = value.componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: "1234567890,.").invertedSet)
            var decimalString = "".join(components) as NSString
    
            let number = NSDecimalNumber(string: decimalString, locale:NSLocale.currentLocale())
    
            var formatter = NSNumberFormatter()
            formatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle
            formatter.locale = NSLocale.currentLocale()
    
            if let formatedValue = formatter.stringFromNumber(number) {
                textField.text = formatedValue
            }
            else {
                textField.text = ""
            }
    }
    

提交回复
热议问题