I've been working on a SwiftUI app's localization, and I faced a localization-related situation which I don't quite understand (given, I'm not too proficient in SwiftUI yet, to begin with)
As far as I understand, at least in iOS 14, SwiftUI pretty much automatically applies localization to all "normal" strings (as long as I have proper localization files set up - which I do). However, I have two instances of the same string literal - one gets automatic localization treatment. The other does not.
So here's the situation I'm trying to figure out.
I have the following code:
NavigationView {
NavigationLink(destination: CalendarSettingsView()) {
SettingsNavLinkView(label: "Calendar") // <- this doesn't get localized
}
}
And SettingsNavLinkView is set up as the following (just the skeleton related to question):
struct SettingsNavLinkView: View {
var label:String
var body: some View {
Text(label) // <- localized "Calendar" is expected to be passed here
}
}
In addition, CalendarSettingsView defines its title as in:
struct CalendarSettingsView: View {
var body: some View {
ScrollView {
//some code
}
.navigationBarTitle("Calendar", displayMode: .inline) // <- "Calendar" here does get localized
}
}
I do have key entry for "Calendar" in my localization files.
What is happening (and what I don't understand) is for the SettingsNavLinkView(label: "Calendar") component, the "Calendar" is NOT getting localized, HOWEVER, for CalendarSettingsView component (and related use case: .navigationBarTitle("Calendar", displayMode: .inline)) the "Calendar" string DOES get localized.
Both of these instances seem like the very same String to me, so I'm just trying to figure out what's going on here.
I did solve the issue by modifying the SettingsNavLinkView by specifically adding LocalizedStringKey initialization like below:
struct SettingsNavLinkView: View {
var label:String
let localizedLabel = LocalizedStringKey(label) // <-- NEW
var body: some View {
Text(localizedLabel) // <-- UPDATED to use localizedLabel instead of label
}
}
But why did I have to do that? Why wasn't the "Calendar" string automatically localized at the point when it was passed to the SettingsNavLinkView as per this code SettingsNavLinkView(label: "Calendar")?
A bug in SwiftUI localization? My incomplete understanding of how localization works?
I would prefer not having to resort to LocalizedStringKey for "simple strings"… But I'm not sure if what I'm asking for is even valid from the perspective of how "automatic" localization really works.
Any thoughts appreciated. Thanks!