我正在寻找一种满足以下条件的文本字段货币格式化程序:
我尝试了很多解决方案:
使用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
}
使用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
}
答案 0 :(得分:1)
好吧,看来您的担心可以通过对您的第一个解决方案进行第一轮实施来解决,您只需考虑,
和.
的本地化。这很容易,您可以通过许多不同的方式来实现它,但是重要的部分是您的应用程序已本地化,例如,假设两种语言处理小数和千位时使用不同的符号(让我们以这些语言为英语和意大利语为例) ):
,
处理小数点,使用.
处理千位.
处理小数点,使用,
处理千位 A)您可以做的是创建一个Localizable.strings
文件,然后以英语和意大利语为例对项目进行本地化。为此,请在此处添加语言。
B)然后转到您的Localizable.strings
文件,并localize
找到您支持的语言(例如英语和意大利语),就像这张图片中对德语和英语所做的一样
现在您将得到两个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。只是向您展示如何通过在应用程序中使用“本地化”来针对不同的语言以不同的方式操作某些符号。