带variablesSwift的NSLocalizedString

我想弄清楚如何使用variables的NSLocalizedString。

例如,如果我想在“我的Localizable.strings文件中输出“by Peter and Larry”,我应该具有以下内容吗?

 "account.by_user" = "by %@ and %@"; 

我将如何调用NSLocalizedString("account.by_user", comment: "") ,如果有2个variablesname1name2其中name1 =彼得和name2 =拉里?

是的,你应该有"account.by_user" = "by %@ and %@"; 并采取这一点:

 let myString = String(format: NSLocalizedString("account.by_user", comment: "any comment"), "Peter","Larry") 

这是另一种方式,我是如何做到的。

 let myString = String.localizedStringWithFormat(NSLocalizedString("by %@ and %@", comment: "yourComment"), name1, name2) 

基本上,格式化本地化string的主要思想是这样的:

 let math = "Math" let science = "Science" String.localizedStringWithFormat(NSLocalizedString("I love %@ and %@", comment: "loved Subjects"), math, science) 

在下面添加一个小样本,因为这花了我一些时间来定位Localizable.strings文件格式。

将variables添加到本地化string的示例:

在代码中:

 let myVar: String = "My Var" String(format: NSLocalizedString("translated_key %@", comment: "Comment"), myVar) 

在Localizable.strings文件中:

 "translated_key %@" = "My var is: %@"; 

当然,右侧的%@可以replace:

 "translated_key %@" = "My var is: %@"; "translated_key %@" = "%@ is my var"; "translated_key %@" = "I use %@ as my var"; 

另外, %@可以被%dreplace为int,或者%freplace为一个float。