【发布时间】:2019-04-18 11:52:21
【问题描述】:
我正在寻找满足以下条件的文本字段货币格式化程序:
- 它应该被格式化(逗号分隔)我正在输入
- 小数点前10位,后2位,应允许
- 它应该允许 (2) 的正则表达式
- 当我们剪切时,光标应该保持在同一位置
- 当我们在货币中间键入时,光标不应向左移动。
- 它应该支持正则表达式中的本地化(逗号和句点)。
我尝试了很多解决方案:
-
使用
NSCharacterSet(这是最接近的,但由于在本地化过程中.和,互换,正则表达式在此处失败,而且我们在此处使用.decimal类型以避免文本字段中的$)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
}
【问题讨论】:
-
当然,您必须使用您的代码来满足上述要求。但这里有几个有用的链接 1.stackoverflow.com/questions/15217124/… 2.reddit.com/r/swift/comments/6d4krx/…
-
请发布代码而不是图片,除非您想在编译器代码中显示一些警告。
-
@denis_lor 请检查
标签: ios swift regex uitextfield currency-formatting