iOS:如何使用多个插值参数本地化字符串?

Chr*_*ris 4 localization objective-c internationalization nslocalizedstring ios

我如何使用NSLocalizedString构建具有多个参数的字符串,同时让翻译器控件根据需要更改顺序?

我的Localizable.string中的一个示例是:

"score_out_of"="Your score is %i out of %i";
Run Code Online (Sandbox Code Playgroud)

并且会像

[NSString stringWithFormat:NSLocalizedString(@"score_out_of", nil), correct, total];
Run Code Online (Sandbox Code Playgroud)

但是在某些语言环境中,语法规则可能会规定总数必须正确。在目标C中,插值顺序似乎是硬编码的。

在其他语言中,这是通过命名参数来实现的,例如在ruby中将其定义为:

out_of: "Your score is %{correct} out of %{total}"
Run Code Online (Sandbox Code Playgroud)

并像这样调用:

I18n('out_of', {total: total, correct: correct})
Run Code Online (Sandbox Code Playgroud)

在iOS / Objective C上完成相同任务的推荐方法是什么?

小智 6

根据文档

https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html#//apple_ref/doc/uid/TP40004265-SW2

请注意,您还可以使用“ n $”位置说明符,例如%1 $ @%2 $ s

因此,您只需将字符串创建为

"score_out_of"="Your score is %1$i out of %2$i"

用其他语言来说,可能是

"score_out_of"="Out of %2$i, your score is %1$i"