所以我使用我在SO上找到的NSString扩展来本地化项目。该扩展名如下:
extension String {
var localized: String {
return NSLocalizedString(self, tableName: nil, bundle: NSBundle.mainBundle(), value: "", comment: "")
}
}
但是我在Localizable.strings列表中遇到了包含参数的字符串。例如:
"explore_item_desc1" = "Welcome to rent my %1$s!";
在我能够做到这一点之前:
uiLabel.text = "localizedString".localized
如何为保存参数的字符串执行类似的操作?
答案 0 :(得分:2)
您的本地化密钥应如下所示:
"localized_key_name1" = "foo";
"localized_key_name2" = "%@ foo %@";
将localized
变量改为函数
extension String {
var localized: String {
return NSLocalizedString(self, tableName: nil, bundle: NSBundle.mainBundle(), value: "", comment: "")
}
func localized(args : CVarArgType...) -> String {
return withVaList(args, { (f:CVaListPointer) -> String in
(NSString.init(format:NSLocalizedString(self, comment:""), arguments: f) as String)
})
}
}
不带参数的使用
uiLabel.text = "localized_key_name1".localized // "foo"
使用参数
uiLabel.text = "localized_key_name2".localized("param1", "param2") // "param1 foo param2"