【问题标题】:SwiftUI preview issue while using environment locale使用环境语言环境时出现 SwiftUI 预览问题
【发布时间】:2020-05-03 17:18:58
【问题描述】:

我正在使用一个简单的视图在 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 显示货币和€,正如我已经在预览中的语言环境中提到的那样。

【问题讨论】:

    标签: localization swiftui nsnumberformatter


    【解决方案1】:

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

    【讨论】:

    • 这是否意味着,我们将不得不传递 Locale 对象,如果没有它,Swift UI Preview 将不会以预期的语言环境格式显示?
    猜你喜欢
    • 2023-03-27
    • 1970-01-01
    • 2014-04-16
    • 1970-01-01
    • 2012-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多