使用环境语言环境时出现 SwiftUI 预览问题

SwiftUI preview issue while using environment locale

我正在使用一个简单的视图在 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 中的货币和欧元,正如我在预览中的区域设置中提到的那样。

这是一个解决方案。使用 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
    }
}