我想在输入数字时向文本字段添加数千个分隔符。我的想法是对 onChange 事件做出反应,格式化输入的数字,然后将格式化的文本写入文本字段:
import Foundation
import SwiftUI
struct TestFormatTextFieldView: View {
@State private var stringAmount: String = ""
var body: some View {
NavigationStack {
Form {
TextField("Amount", text: $stringAmount)
.keyboardType(.numbersAndPunctuation)
.onChange(of: stringAmount, perform: { newValue in
stringAmount = formatDouble(input: newValue)
})
Button("Request price") {
self.requestPrice()
}
}
}
}
func formatDouble(input : String) -> String {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.maximumFractionDigits = 2
// If the String can't be cast as a Double return ""
guard let resultAsDouble = Double(input) else {
return ""
}
let result = formatter.string(from: NSNumber(value: resultAsDouble)) ?? ""
print("formatted \(result)")
return result
}
func requestPrice() {
print("request \(stringAmount)")
}
}
struct TestFormatTextFieldView_Prev: PreviewProvider {
static var previews: some View {
ContentView()
}
}
如果我写的数字超过 4 位,我会得到以下错误: onChange(of: String) 动作尝试每帧更新多次。 问题是格式化会改变文本的长度。是否仍然可以即时添加数千个分隔符?