输入时在文本字段中设置货币格式

问题描述 投票:0回答:1

我需要在输入

TextField
时格式化货币。我尝试了很多答案,但对我的情况没有任何作用。我的货币是印度卢比。当用户键入时,它应该从“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)
swift swiftui textfield nsnumberformatter
1个回答
2
投票
一旦字符串中有

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)
}
© www.soinside.com 2019 - 2024. All rights reserved.