Xcode 版本 15.0 设置为 iOS 15.0 正如标题所示,我的应用程序使用 Text(someAmount, format: Locale.current.currencyCode ?? "GBP") 来显示货币数量,其符号应针对每个用户区域设置进行更改。然而,在预览中我得到了美元,并且无法找到更改为仅用于预览的特定区域设置的方法。
我发现了一些示例代码,我必须稍微修改一下才能使其运行,但这会更改非预览代码并且是固定数量。
// App.swift file
import SwiftUI
@main
struct Locale_TestApp: App {
@StateObject var someCurrency = Currency()
var body: some Scene {
WindowGroup {
ContentView(currency: someCurrency)
}
}
}
// ContentView code.
import SwiftUI
class Currency: ObservableObject {
let currencyValue: Double = 123.45
func getFormattedCurrency(for locale: Locale) -> String{
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.locale = locale
let formatterCurrency = formatter.string(for: self.currencyValue) ?? "?"
return formatterCurrency
}
}
struct ContentView: View {
@Environment(\.locale) var locale
let currency: Currency
var body: some View {
Text(currency.getFormattedCurrency(for: locale)) // Prints £123.45 for en_GB
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView(currency: Currency())
.environment(\.locale, .init(identifier: "en_GB"))
}
}
如果我仅将 .environment(.locale, .init(identifier: "en_GB")) 行添加到预览中的 ContentView() 中,则发生的所有情况都是 $ 更改为 US$。
是否可以将预览设置为特定区域设置,而保留“正常”代码?
struct ContentView: View {
@Environment(\.locale) var locale
let currencyValue = 123.45
var body: some View {
Text(currencyValue, format: .currency(code: locale.currency?.identifier ?? "USD")
}
}
仅供参考
@StateObject
用于异步组合管道,您可能不需要它。