格式化货币-Swift

时间:2019-04-18 11:52:21

标签: ios swift regex uitextfield currency-formatting

我正在寻找一种满足以下条件的文本字段货币格式化程序:

  1. 应格式化(以逗号分隔)我正在键入
  2. 小数点前10位和小数点后2位
  3. 它应该允许(2)的正则表达式
  4. 剪切时,光标应留在同一位置
  5. 当我们在货币中间输入时,光标不应向左移动。
  6. 它应支持正则表达式中的本地化(逗号和句点)。

我尝试了很多解决方案:

  1. 使用NSCharacterSet(这是最接近的,但由于本地化过程中.,的互换而使regex失败,我们这里也使用了.decimal类型避免在textField中使用$

    class func checkTextField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        guard let textBeforeEditing = textField.text else {
            return true
        }
        if ((string == "0" || string == "") && (textField.text! as NSString).range(of: ".").location < range.location) {
            return true
        }
        var currentPosition = 0
        if let selectedRange = textField.selectedTextRange {
            currentPosition = textField.offset(from: textField.beginningOfDocument, to: string == "" ? selectedRange.end : selectedRange.start)
        }
        let allowedCharacterSet = NSCharacterSet(charactersIn: "0123456789.").inverted
        let filtered = string.components(separatedBy: allowedCharacterSet)
        let component = filtered.joined(separator: "")
        let isNumeric = string.replacingOccurrences(of: ",", with: "") == component
        var textFieldString : String = ""
        var numberWithoutCommas : String = ""
        guard isNumeric else {
            return false
        }
        let formatter = NumberFormatter()
        formatter.numberStyle = .decimal
        textFieldString = (textField.text! as NSString).replacingCharacters(in: range, with: string)
        numberWithoutCommas = textFieldString.replacingOccurrences(of: ",", with: "")
        let formattedNumberWithoutCommas = formatter.number(from: numberWithoutCommas)
        guard let formattedNumber = formattedNumberWithoutCommas, var formattedString = formatter.string(from: formattedNumber) else {
            textField.text = nil
            return false
        }
        if string == "." && range.location == textField.text?.count {
            formattedString = formattedString.appending(".")
        }
        textField.text = formattedString
        currentPosition = getCursorPositionForTextField(string: string, cursorPosition: currentPosition, formattedString: formattedString, textBeforeEditing: textBeforeEditing)
        handleTextFieldCursor(cursorPosition: currentPosition, textField: textField)
        return false
    }
    
  2. 使用NumberFormatter,但光标会在每次剪切/粘贴时移至结束

    extension String {
    
        func currencyInputFormatting() -> String {
    
            var number: NSNumber!
            let formatter = NumberFormatter()
            formatter.numberStyle = .currency
            formatter.maximumFractionDigits = 2
            formatter.minimumFractionDigits = 2
    
            var amountWithPrefix = self
    
            // remove from String: "$", ".", ","
            let regex = try! NSRegularExpression(pattern: "[^0-9]", options: .caseInsensitive)
            amountWithPrefix = regex.stringByReplacingMatches(in: amountWithPrefix, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, self.characters.count), withTemplate: "")
    
            let double = (amountWithPrefix as NSString).doubleValue
            number = NSNumber(value: (double / 100))
    
            guard number != 0 as NSNumber else {
                return ""
            }
    
            return formatter.string(from: number)!
        }
    }
    

我花了将近一两天的时间来找到100%可行的解决方案,但无法解决。 任何帮助将不胜感激

编辑

@denis_lor 答案的帮助下,我已经非常接近解决方案,但仍然无法实现逗号与句点的互换。这是我的更新代码,我缺少什么吗?它适用于英语,但不适用于西班牙语。

class func checkTextField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    guard let textBeforeEditing = textField.text else {
        return true
    }
    if ((string == "0" || string == "") && (textField.text! as NSString).range(of: "\(NSLocalizedString("core_decimal_separator_symbol", comment: ""))").location < range.location) {
        return true
    }
    var currentPosition = 0
    if let selectedRange = textField.selectedTextRange {
        currentPosition = textField.offset(from: textField.beginningOfDocument, to: string == "" ? selectedRange.end : selectedRange.start)
    }
    let allowedCharacterSet = NSCharacterSet(charactersIn: "0123456789\(NSLocalizedString("core_decimal_separator_symbol", comment: ""))").inverted
    let filtered = string.components(separatedBy: allowedCharacterSet)
    let component = filtered.joined(separator: "")
    let isNumeric = string.replacingOccurrences(of: NSLocalizedString("core_thousand_separator_symbol", comment: ""), with: "") == component
    var textFieldString : String = ""
    var numberWithoutCommas : String = ""
    guard isNumeric else {
        return false
    }
    let formatter = NumberFormatter()
    formatter.numberStyle = .decimal
    textFieldString = (textField.text! as NSString).replacingCharacters(in: range, with: string)
    numberWithoutCommas = textFieldString.replacingOccurrences(of: NSLocalizedString("core_thousand_separator_symbol", comment: ""), with: "")
    let formattedNumberWithoutCommas = formatter.number(from: numberWithoutCommas)
    guard let formattedNumber = formattedNumberWithoutCommas, var formattedString = formatter.string(from: formattedNumber) else {
        textField.text = nil
        return false
    }
    if string == NSLocalizedString("core_decimal_separator_symbol", comment: "") && range.location == textField.text?.count {
        formattedString = formattedString.appending(NSLocalizedString("core_decimal_separator_symbol", comment: ""))
    }
    textField.text = formattedString
    currentPosition = getCursorPositionForTextField(string: string, cursorPosition: currentPosition, formattedString: formattedString, textBeforeEditing: textBeforeEditing)
    handleTextFieldCursor(cursorPosition: currentPosition, textField: textField)
    return false
}

1 个答案:

答案 0 :(得分:1)

好吧,看来您的担心可以通过对您的第一个解决方案进行第一轮实施来解决,您只需考虑,.的本地化。这很容易,您可以通过许多不同的方式来实现它,但是重要的部分是您的应用程序已本地化,例如,假设两种语言处理小数和千位时使用不同的符号(让我们以这些语言为英语和意大利语为例) ):

  • [en]语言使用,处理小数点,使用.处理千位
  • [it]语言使用.处理小数点,使用,处理千位

A)您可以做的是创建一个Localizable.strings文件,然后以英语和意大利语为例对项目进行本地化。为此,请在此处添加语言。 enter image description here

B)然后转到您的Localizable.strings文件,并localize找到您支持的语言(例如英语和意大利语),就像这张图片中对德语和英语所做的一样 enter image description here

现在您将得到两个Localizable.strings,一个用于英语,一个用于意大利语:

Localizable.strings(英语)

core_decimal_separator_symbol = ",";
core_thousand_separator_symbol = ".";

Localizable.strings(意大利语)

core_decimal_separator_symbol = ".";
core_thousand_separator_symbol = ",";

C)并且在您的代码中,您需要寻址的所有地方,例如您的小数分隔符,而不是对其进行硬编码,您可以执行以下操作:

removeDecimalSeparator = numberAsString.replacingOccurrences(of: NSLocalizedString("core_decimal_separator_symbol", comment: ""), with: "")

例如,每当您的应用程序本地化为英语时,此代码就会翻译为:

removeDecimalSeparator = numberAsString.replacingOccurrences(of: ",", with: "")

例如,当您的应用本地化为意大利语时,此代码将翻译为:

removeDecimalSeparator = numberAsString.replacingOccurrences(of: ".", with: "")

总结:考虑这些作为示例,同时考虑到我们在此答案中得到的Localizable.strings。只是向您展示如何通过在应用程序中使用“本地化”来针对不同的语言以不同的方式操作某些符号。