swift - Swift 数字格式器货币问题
问题描述
例如,我希望我的 textField 显示5.000,00
,我设法限制我的用户可以输入的字符,但我的货币不起作用。另外我是 Swift 的新手,如何让这种货币发挥作用?
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.allowsFloats = true
formatter.currencyDecimalSeparator = ","
formatter.alwaysShowsDecimalSeparator = true
formatter.locale = Locale(identifier: "pt_BR")
formatter.currencyCode = "BRL"
formatter.maximumFractionDigits = 0
let currentText = textField.text ?? ","
guard let stringRange = Range(range, in: currentText) else { return false}
let updatedText = currentText.replacingCharacters(in: stringRange, with: string)
if let groupingSeparator = formatter.groupingSeparator {
if string == groupingSeparator {
return true
}
if let textWithoutGroupingSeparator = textField.text?.replacingOccurrences(of: groupingSeparator, with: "") {
var totalTextWithoutGroupingSeparators = textWithoutGroupingSeparator + string
if string.isEmpty { // pressed Backspace key
totalTextWithoutGroupingSeparators.removeLast()
}
if let numberWithoutGroupingSeparator = formatter.number(from: totalTextWithoutGroupingSeparators),
let formattedText = formatter.string(from: numberWithoutGroupingSeparator) {
textField.text = formattedText
return false
}
return updatedText.count <= 8
}
}
return true
}
解决方案
我用字符串扩展解决了这个问题,以前我在我的视图控制器上使用了一个函数,这样做为我解决了,你只需要改变你的语言环境就可以了。
扩展字符串 {
// formatting text for currency textField
func currencyInputFormatting() -> String {
var number: NSNumber!
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.locale = Locale(identifier: "pt_BR")
formatter.currencySymbol = ""
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.count), withTemplate: "")
let double = (amountWithPrefix as NSString).doubleValue
number = NSNumber(value: (double / 100))
// if first number is 0 or all numbers were deleted
guard number != 0 as NSNumber else {
return ""
}
print(formatter.string(from: number))
return formatter.string(from: number)!
}
}
推荐阅读
- wordpress - add_action 没有 do_action?
- vue.js - 构建的 Vue 应用程序允许 Webpack 查看源代码
- google-maps - Google Directions API - 相同请求的不同结果但具有重新排序的参数
- java - 在虚拟机上安装 CentOS 的 Intellij IDEA 中运行 Spark 作业
- python - 混合模式 CSV 导入 Pyspark
- jquery-selectors - 将 Cypress cy.get() 与包含选择器一起使用未按预期工作
- python - 尝试将值列表作为新列附加到现有 json 文件
- sql - 服务代理占用非常高的总运行时间
- c++ - 可变参数模板作为第一个参数
- powerbi - 如何摆脱 PowerBI 中的 100% 计算