SwiftUI - Localization of a dynamic Text

浪尽此生 提交于 2021-01-05 07:20:25

问题


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.


回答1:


Use NSLocalizedString, like

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


来源:https://stackoverflow.com/questions/61684038/swiftui-localization-of-a-dynamic-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!