Search code examples
swiftlocalizationswiftui

SwiftUI - Localization of a dynamic Text


I am struggling with the locilization of some of my TextFields. Usually a "normal" localization of a Text() or TextField() works without any problem in my App if the text I want to translate is hardcoded like this:

Text("English Text")

I translate it in my Localizable.strings like this:

"English Text" = "German Text";

Now I want to translate TextFields which are more dynamic, but where I know each possible entry:

                TextField("New note" + (refresh ? "" : " "),text: $newToDo, onCommit: {
                    self.addToDo()
                    self.refresh.toggle()
                })

(The refresh is necessary because of a SwiftUI bug sometimes not showing the placeholder-text again.)

Another example would be:

    func dayWord() -> String {
        let dateFormatter = DateFormatter()
        dateFormatter.timeZone = TimeZone.current
        dateFormatter.locale = Locale(identifier: "de_DE")
        dateFormatter.dateFormat = "EEEE"
        return dateFormatter.string(from: self)
    }

    var day: String {
        return data.date.dateFromMilliseconds().dayWord()
    }

   Text(day.prefix(2))

The Text(day.prefix(2)) has only seven possible states, but I don't know what to write as a key in my Localizable.strings.


Solution

  • Use NSLocalizedString, like

    TextField(NSLocalizedString("New note", comment: "") + (refresh ? "" : " "), ...