Search code examples
localizationswiftuinsnumberformatter

SwiftUI preview issue while using environment locale


I am using a simple view to display text in NumberFormatter for a specific locale

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
    }
}

I was expecting the preview will show currency in French with € as I have already mentioned in Locale in preview.


Solution

  • Here is a solution. Tested with Xcode 11.4

    demo

    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
        }
    }