• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

在Swift格式化本地化字符串

用户头像
it1352
帮助1

问题说明

我正在学习将我的应用本地化为简体中文。我正在关注如何执行本教程

I am learning to localise my app to Simplified Chinese. I am following this tutorial on how to do this.

由于本教程基于Obj-C,格式化的字符串可以这样写:

Because the tutorial is based on Obj-C, formatted strings can be written like this:

"Yesterday you sold %@ apps" = "Ayer le vendió %@ aplicaciones";

你喜欢? =~Es bueno?〜;

"You like?" = "~Es bueno?~";

但我使用的是Swift。在Swift中,我认为你不能使用%@ 来表明那里有东西放在那里。我们有字符串插值吗?

But I am using Swift. And in Swift I don't think you can use %@ to indicate that there is something to be placed there. We have string interpolation right?

我的应用程序与数学有关。我想显示哪些输入用于计算表格视图单元格的详细标签中的结果。例如

My app is kind of related to maths. And I want to display which input(s) is used to compute the result in a detailed label of a table view cell. For example

--------------
1234.5678
From x, y <---- Here is the detailed label
--------------

这里,从x,y 表示结果是从x和y计算的。我想把它翻译成中文:

Here, From x, y means "The result is computed from x and y". I want to translate this to Chinese:

从 x, y 得出

之前,我可以使用这个:

Before, I can just use this:

"From \(someVariable)"

使用字符串文件:

"From" = "从 得出";

这就是我在代码中使用它的方式

And this is how I would use it in code

"\(NSLocalizedString("From", comment: "")) \(someVariable)"

但是如果在中文版本中使用它,最终字符串将是这样的:

But if this were used in the Chinese version, the final string will be like this:

"从 得出 x, y"

我的意思是我可以把<字符串文件中的两个不同条目中的code>从和得出。但是有更好的方法吗?

I mean I can put the and 得出 in two different entries in the strings file. But is there a better way to do it?

正确答案

#1

可以使用%@ 在Swift的字符串(格式:...)中,它可以用Swift

You can use %@ in Swift's String(format:...), it can be substituted by a Swift String or any instance of a NSObject subclass. For example, if the Localizable.strings file contains the definition

"From %@, %@" = "从 %@, %@ 得出";

然后

let x = 1.2
let y = 2.4
let text = String(format: NSLocalizedString("From %@, %@", comment: ""), "\(x)", "\(y)")
// Or alternatively:
let text = String(format: NSLocalizedString("From %@, %@", comment: ""), NSNumber(double: x), NSNumber(double: y))

产生从1.2,2.4得出。另一个选择是使用
%f 格式表示双浮点数:

produces "从 1.2, 2.4 得出". Another option would be to use the %f format for double floating point numbers:

"From %f, %f" = "从 %f, %f 得出";

with

let text = String(format: NSLocalizedString("From %f, %f", comment: ""), x, y)

请参阅 Niklas的回答
以获得更好的本地化解决方案数字代表

See Niklas' answer for an even better solution which localizes the number representation as well.

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhcfkhbk
系列文章
更多 icon
同类精品
更多 icon
继续加载