我正在使用一个简单的视图来显示在 NumberFormatter
某个特定地点的
struct CurrencyView: View {
let currency:Currency
var body: some View {
Text(currency.getFormattedCurrency())
}
}
struct CurrencyView_Previews: PreviewProvider {
static var previews: some View {
CurrencyView(currency: Currency(currencyValue: 1.0)).previewLayout(.fixed(width: 300.0, height: 55.0)).environment(\.locale, .init(identifier: "fr_Fr"))
}
}
struct Currency{
let currencyValue:Double
func getFormattedCurrency() -> String{
let formatter = NumberFormatter()
formatter.numberStyle = .currency
let formatterCurrency = formatter.string(for: self.currencyValue) ?? ""
return formatterCurrency
}
}
我期待着预览将显示货币在。French
和 €,因为我已经在预览的 Locale 中提到了。
这是一个解决方案。用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
}
}