iOS: How to localize strings with multiple interpolated parameters?

爷,独闯天下 提交于 2019-12-19 19:50:23

问题


How do I use NSLocalizedString to build a string with multiple parameters while giving the translator control to change the order if they wish?

An example in my Localizable.string is:

"score_out_of"="Your score is %i out of %i";

And would be invoked like

[NSString stringWithFormat:NSLocalizedString(@"score_out_of", nil), correct, total];

But on some locales the grammar rules might dictate that total goes before correct. In Objective C it seems the interpolation order is hard coded.

In other languages this is accomplished by naming the parameters, for example in ruby it would be defined like:

out_of: "Your score is %{correct} out of %{total}"

And invoked like:

I18n('out_of', {total: total, correct: correct})

What is the recommended way to accomplish the same thing on iOS / Objective C?


回答1:


According to the documentation

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

Note that you can also use the “n$” positional specifiers such as %1$@ %2$s

So you can simply create your string as

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

And in other language, it could be

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



来源:https://stackoverflow.com/questions/24160675/ios-how-to-localize-strings-with-multiple-interpolated-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!