在文本字段中输入时需要设置货币格式。我尝试了很多答案,但对我的情况没有任何作用。我的货币是印度卢比。当用户输入时,它应该从 1200 更改为 1,200 卢比。我可以将其转换为 £1200,但缺少逗号。
我的实现:
extension NumberFormatter{
static var currencyFormatter: NumberFormatter {
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.currencySymbol = "₹"
formatter.maximumFractionDigits = 0
formatter.usesGroupingSeparator = true
formatter.currencyCode = "INR"
formatter.currencyGroupingSeparator = ","
formatter.groupingSeparator = ","
formatter.maximumIntegerDigits = 10
formatter.locale = Locale(identifier: "en_IN")
return formatter
}}
@State var testAmount = String()
TextField("₹ 0", text: $testAmount)
.onChange(of: testAmount){newvalue in
if let parsedAmount = Double(newvalue){
self.testAmount = NumberFormatter.currencyFormatter.string(from: NSNumber(value: parsedAmount)) ?? ""
}
}
.keyboardType(.numberPad)
Double(newvalue)
,
₹
将无法解析该字符串。
您可以使用
FormatStyle
API 解析和格式化数字。您可以使用Decimal.FormatStyle.Currency
。
@State private var testAmount = ""
let formatStyle = Decimal.FormatStyle.Currency
.currency(code: "INR")
.precision(.fractionLength(0))
.locale(.init(identifier: "en_IN"))
var body: some View {
TextField("₹ 0", text: $testAmount)
.onChange(of: testAmount){ _, newValue in
if let parsedAmount = try? formatStyle.parseStrategy.parse(newValue) {
self.testAmount = formatStyle.format(parsedAmount)
}
}
}
但在我看来,打字时格式化相当令人困惑。用户结束编辑后进行格式化是一种更好的用户体验。
TextField
有一个专用初始化程序:
@State private var testAmount: Decimal = 0
let formatStyle = Decimal.FormatStyle.Currency
.currency(code: "INR")
.precision(.fractionLength(0))
.locale(.init(identifier: "en_IN"))
var body: some View {
TextField("₹ 0", value: $testAmount, format: formatStyle)
}