ios - 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 search
andthe search engine
或 the the process of searching
,在德语中可以翻译Suchen
为前者和Suche
后者。在那种情况下Text("Search")
,不足以涵盖这些情况。我知道我可以使用NSLocalizedString("Search", comment: "verb")
and NSLocalizedString("Search", comment: "the process of searching")
,但是本地化条目的 ID 将由string
and组成comment
。
解决方案
事实证明这很容易。我所要做的就是value
在NSLocalizedString.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>
推荐阅读
- html - 谷歌浏览器中奇怪的下拉选项
- node.js - 在系统上创建/设置 React Native 项目时面临的问题
- python - 熊猫数据框到 CSV python
- c# - 如何从 Outlook 日历中获取数据?
- android - 程序类型已存在:迁移到 Androidx 后的 com.google.common.util.concurrent.ListenableFuture
- laravel - Laravel php artisan 显示另一个弹出窗口,这是一个错误吗?
- python - YouTube API nextPageToken 返回不可用的结果
- shopify - Shopify Liquid - 字符串上的 Forlooping
- javascript - node-mysql2 finally 块和 connection.end() 不想被调用
- jmeter-4.0 - 用于 Cognito 应用程序的 JMeter 脚本问题