NNi*_*ikN 5 localization nsnumberformatter swiftui
我正在使用一个简单的视图来显示文本NumberFormatter我正在使用一个简单的视图来显示特定区域
struct CurrencyView: View {\n let currency:Currency\n var body: some View {\n Text(currency.getFormattedCurrency())\n }\n}\n\nstruct CurrencyView_Previews: PreviewProvider {\n static var previews: some View {\n CurrencyView(currency: Currency(currencyValue: 1.0)).previewLayout(.fixed(width: 300.0, height: 55.0)).environment(\\.locale, .init(identifier: "fr_Fr"))\n }\n}\n\nstruct Currency{\n let currencyValue:Double\n\n func getFormattedCurrency() -> String{\n let formatter = NumberFormatter()\n formatter.numberStyle = .currency\n let formatterCurrency = formatter.string(for: self.currencyValue) ?? ""\n return formatterCurrency\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n\n我预计预览会显示货币French\xe2\x82\xac 中的货币,正如我在预览中的区域设置中提到的那样。
这是一个解决方案。使用 Xcode 11.4 进行测试
struct CurrencyView: View {
@Environment(\.locale) var locale
let currency:Currency
var body: some View {
Text(currency.getFormattedCurrency(for: locale))
}
}
struct CurrencyView_Previews: PreviewProvider {
static var previews: some View {
CurrencyView(currency: Currency(currencyValue: 1.0))
.environment(\.locale, .init(identifier: "fr_Fr"))
.previewLayout(.fixed(width: 300.0, height: 55.0))
}
}
struct Currency{
let currencyValue:Double
func getFormattedCurrency(for locale: Locale) -> String{
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.locale = locale
let formatterCurrency = formatter.string(for: self.currencyValue) ?? ""
return formatterCurrency
}
}
Run Code Online (Sandbox Code Playgroud)