Ios SwiftUI中的NumberFormatter-未解析标识符的使用';格式化程序&x27;
在我的SwiftUI应用程序中,我需要使用货币。我正在尝试使用NumberFormatter,但出现错误: 使用未解析的标识符“格式化程序” 在线:Ios SwiftUI中的NumberFormatter-未解析标识符的使用';格式化程序&x27;,ios,swift,formatting,swiftui,number-formatting,Ios,Swift,Formatting,Swiftui,Number Formatting,在我的SwiftUI应用程序中,我需要使用货币。我正在尝试使用NumberFormatter,但出现错误: 使用未解析的标识符“格式化程序” 在线: self.valueAsString = formatter.string(for: self.value) 以下是我的代码: import SwiftUI struct ContentView: View { @State private var newValueAsString = "" @State p
self.valueAsString = formatter.string(for: self.value)
以下是我的代码:
import SwiftUI
struct ContentView: View {
@State private var newValueAsString = ""
@State private var value: NSDecimalNumber = 0
@State private var valueAsString = "0.0"
let decimalBehavior = NSDecimalNumberHandler(roundingMode: .plain, scale: 2, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: true)
private var currencyFormat: NumberFormatter = {
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.usesSignificantDigits = true
formatter.minimumSignificantDigits = 1 // default
formatter.maximumSignificantDigits = 6 // default
return formatter
}()
var body: some View {
VStack {
TextField("0", text: $newValueAsString, onCommit: {
self.value = NSDecimalNumber(string: self.newValueAsString, locale: Locale.current).rounding(accordingToBehavior: self.decimalBehavior)
self.valueAsString = formatter.string(for: self.value)
// Tried this too:
// self.valueAsString = "\(formatter.string(for: self.value))"
}
)
.multilineTextAlignment(.trailing)
.font(Font.system(size: 30))
.keyboardType(.decimalPad)
// Just to test. Later I will save the value to Core Data.
Text("\(self.value)")
Text("\(self.valueAsString)")
}
.padding()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
我想做的是:
self.valueAsString = self.currencyFormat.string(for: self.value)
伟大的它起作用了。谢谢:)我刚刚编辑了你的答案,添加了??“0”
为可选值提供默认值