首页 > 解决方案 > SwiftUI 本地化 - 如何使 UI 组件及其功能成为本地化的基础

问题描述

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

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

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 searchandthe search engine或 the the process of searching,在德语中可以翻译Suchen为前者和Suche后者。在那种情况下Text("Search"),不足以涵盖这些情况。我知道我可以使用NSLocalizedString("Search", comment: "verb")and NSLocalizedString("Search", comment: "the process of searching"),但是本地化条目的 ID 将由stringand组成comment

标签: iosiphoneswiftuilocalizationinternationalization

解决方案


事实证明这很容易。我所要做的就是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")

en.xliff

<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")

en.xliff

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

推荐阅读