Reputation: 21
I would like to dynamically specify the unit to be used (e.g. hours, minutes, seconds) in the Strings Dictionary when called:
Text("\(unit) \(value))", tableName: "SingularAndPlural")
unit
contains the unit as a stringvalue
contains the value as an integerBut that doesn't work, it doesn't resolve.
I've tried all possible variants, but I can't get any further.
Upvotes: 2
Views: 94
Reputation: 53161
Rather than use stringsDict
you should probably use localisation provided by the built-in Formatters. In this case DateComponentsFormatter
probably does what you need:
struct ContentView: View {
var body: some View {
List {
ForEach(["en", "ru", "el", "th"], id: \.self) { localeId in
Section(localeId) {
ForEach(0..<3, id: \.self) { i in
HStack {
Text(formatter(localeId).string(from: DateComponents(minute: i))!)
Spacer()
Text(formatter(localeId).string(from: DateComponents(second: i))!)
}
}
}
}
}
}
func formatter(_ localeId: String) -> DateComponentsFormatter {
var calendar = Calendar.current
calendar.locale = Locale(identifier: localeId)
let formatter = DateComponentsFormatter()
formatter.calendar = calendar
formatter.unitsStyle = .full
return formatter
}
}
It's even simpler if you just want to format for the device's current locale:
struct ContentView: View {
var body: some View {
List {
ForEach(0..<3, id: \.self) { i in
HStack {
Text(DateComponents(minute: i), formatter: Self.formatter)
Spacer()
Text(DateComponents(second: i), formatter: Self.formatter)
}
}
}
}
static var formatter: DateComponentsFormatter {
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .full
return formatter
}
}
Upvotes: 1