如何在 Swift UI 中实现本地化 [英] How to implement localization in Swift UI

查看:28
本文介绍了如何在 Swift UI 中实现本地化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以帮我吗?我在 Swift UI 中找不到任何关于本地化的描述.任何人都可以就如何本地化例如 Text() 提供建议或更好的示例吗?

Can anybody help me? I can't find any description of the localization in Swift UI. Can anyone please give advice or better an example of how to localize for example Text()?

推荐答案

当你查看 documentation for Text 你可以看到它需要 LocalizedStringKey 而不是 String初始化程序:

When you look at documentation for Text you can see that it takes LocalizedStringKey not a String into its initializer:

init(_ key: LocalizedStringKey, tableName: String? = nil, bundle: Bundle? = nil, comment: StaticString? = nil)

它使本地化变得非常简单.您所要做的就是:

It makes localizing very straightforward. All you have to do is:

  • 创建一个类型为Strings File"的新文件,命名为Localizable.strings
  • 选择新文件并导航到右侧面板中的文件检查器,然后单击本地化...
  • 将您的项目文件转到本地化"部分并将另一种语言添加到列表中 - Xcode 将为您创建本地化文件

当您选择Localizable.strings 时,您将看到它包含原始语言和您刚刚添加的语言的文件.这就是您放置翻译的地方,即键 - 本地化文本对.

When you select you Localizable.strings you will see that it contains files for the original language and the language you have just added. That's where you put your translations, i.e. key - localized text pairs.

如果你有这样的文字是你的应用:

If you have a text like this is your app:

Text("Hello World!")

您现在必须将您的翻译添加到Localizable.strings:

You have to now add to your Localizable.strings your translations:

对于您的基本语言:

"Hello World!" = "Hello World!";

以及您的第二语言(在本例中为德语):

and for your second language (in this case German):

"Hello World!" = "Hallo Welt!";

要查看本地化的预览,您可以像这样定义它们:

To see your previews localised you can define them like this:

struct ContentViewView_Previews: PreviewProvider {

    static var previews: some View {
        ForEach(["en", "de"], id: .self) { id in
            ContentView()
                .environment(.locale, .init(identifier: id))
        }
    }
}

这篇关于如何在 Swift UI 中实现本地化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆