Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI Text view not using localized stringsdict file

Tags:

ios

swift

swiftui

Given this view:

struct ContentView: View {
    let count = 1
    var body: some View {
        Text("There are \(count) light(s)")
            .padding()
    }
}

And this Localizable.stringsdict:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>There are %ld light(s)</key>
    <dict>
        <key>NSStringLocalizedFormatKey</key>
        <string>%#@LIGHT_STRING@</string>
        <key>LIGHT_STRING</key>
        <dict>
            <key>NSStringFormatSpecTypeKey</key>
            <string>NSStringPluralRuleType</string>
            <key>NSStringFormatValueTypeKey</key>
            <string>ld</string>
            <key>one</key>
            <string>There is one light</string>
            <key>other</key>
            <string>There are %ld lights</string>
        </dict>
    </dict>
</dict>
</plist>

I would expect the view to say "There is one light". But instead, it says "There are 1 light(s)".

What am I missing?


Attempted Troubleshooting

If I add this function:

    func tr(_ key: String, _ args: CVarArg...) -> String {
        let format = NSLocalizedString(key, comment: "")
        return String(format: format, locale: Locale.current, arguments: args)
    }

And then use this syntax:

        Text(tr("There are %ld light(s)", 1))
            .padding()

Then I get the expected result. So I think the problem is something with the Text view not generating the correct key (as opposed to something wrong with my stringsdict file)

like image 415
Aaron Brager Avatar asked Jan 30 '26 16:01

Aaron Brager


1 Answers

OK, got it working. I had to double check a few things:

  1. Get the correct key for the dict file by typing po LocalizedStringKey("There are \(count) light(s)") in the debugger, which outputted the key About to Update %lld Contact(s) (I was using %ld).
  2. Select the stringsdict file and click Localize… in the file inspector
  3. Name the file Localizable.stringsdict
like image 108
Aaron Brager Avatar answered Feb 01 '26 05:02

Aaron Brager