SwiftUI 本地化 - 如何使 UI 组件及其功能成为本地化的基础

科尔斯

我遵循了有关如何本地化 iOS 应用程序的推荐方法——我使用基本本地化,并将英语设置为开发语言。

所以我有一个这样的结构:

Localizable.strings
|___ Localizable.strings (English)
|___ Localizable.strings (German)
...

现在当我使用类似的东西时,Text("Cancel")我会在以下内容中得到以下内容Localizable.strings (German)

/* No comment provided by engineer. */
"Cancel" = "Abbrechen";

然后我查看了 Facebook 在他们的包(Facebook Login库)中使用的本地化文件,它们看起来像这样:

"ErrorRecovery.Cancel" = "Abbrechen";

ErrorRecovery.Cancel当用户将应用程序语言切换到English(开发语言)时,我知道如何在不渲染的情况下实现这一点吗?

这对我来说更可取,因为基础本身可以用作跨不同平台的 ID(例如,如果我还想本地化我的 Android 应用程序)。此外,有时一种语言中的同一个词并不总是翻译成另一种语言中的同一个词,例如Search可能具有以下含义:to searchthe search enginethe process of searching,在德语中可以将其翻译Suchen为前者和Suche后者。在那种情况下Text("Search")将不足以涵盖这些情况。我知道我可以使用NSLocalizedString("Search", comment: "verb")and NSLocalizedString("Search", comment: "the process of searching"),但是本地化条目的 ID 将由stringand组成comment

科尔斯

事实证明这很容易。我所要做的就是valueNSLocalizedString.init.

NSLocalizedString函数具有以下签名

/// - parameter key: An identifying value used to reference a localized string.
///   Don't use the empty string as a key. Values keyed by the empty string will
///   not be localized.
...
/// - parameter value: A user-visible string to return when the localized string
///   for `key` cannot be found in the table. If `value` is the empty string,
///   `key` would be returned instead.

NSLocalizedString(_ key: String, tableName: String? = nil, bundle: Bundle = Bundle.main, value: String = "", comment: String)

如果value未提供参数,则导出本地化后的翻译条目如下所示:

文件.swift

NSLocalizedString("Cancel", comment: "Cancel button")

压缩文件

<trans-unit id="Cancel" xml:space="preserve">
    <source>Cancel</source>
    <target>Cancel</target>
    <note>Cancel button</note>
</trans-unit>

但是,如果value提供参数,则生成的翻译条目如下所示:

文件.swift

NSLocalizedString("Navigation.Button.Cancel", value: "Cancel", comment: "Cancel button")

压缩文件

<trans-unit id="Navigation.Button.Cancel" xml:space="preserve">
    <source>Cancel</source>
    <target>Cancel</target>
    <note>Cancel button</note>
</trans-unit>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章