是否有一个Swift等效的NSLocalizedString(…)?
在Objective-C中,我们通常使用:
NSString *string = NSLocalizedString(@"key", @"comment");
我如何在Swift中实现同样的目标?我找到了一个函数:
func NSLocalizedString(
key: String,
tableName: String? = default,
bundle: NSBundle = default,
value: String = default,
#comment: String) -> String
但是,它很长,一点也不方便。
我使用下一个解决方案:
1)创建扩展:
extension String {
var localized: String {
return NSLocalizedString(self, tableName: nil, bundle: Bundle.main, value: "", comment: "")
}
}
2)本地化。字符串文件:
"Hi" = "Привет";
3)使用实例:
myLabel.text = "Hi".localized
享受吧!;)
——乌利希期刊指南:
对于带有注释的情况,您可以使用此解决方案:
1)扩展:
extension String {
func localized(withComment:String) -> String {
return NSLocalizedString(self, tableName: nil, bundle: Bundle.main, value: "", comment: withComment)
}
}
2) .strings文件:
/* with !!! */
"Hi" = "Привет!!!";
3)使用:
myLabel.text = "Hi".localized(withComment: "with !!!")
有助于在单元测试中使用:
这是一个简单的版本,可以扩展到不同的用例(例如使用tableNames)。
public func NSLocalizedString(key: String, referenceClass: AnyClass, comment: String = "") -> String
{
let bundle = NSBundle(forClass: referenceClass)
return NSLocalizedString(key, tableName:nil, bundle: bundle, comment: comment)
}
像这样使用它:
NSLocalizedString("YOUR-KEY", referenceClass: self)
或者像这样加一条评论:
NSLocalizedString("YOUR-KEY", referenceClass: self, comment: "usage description")
我使用下一个解决方案:
1)创建扩展:
extension String {
var localized: String {
return NSLocalizedString(self, tableName: nil, bundle: Bundle.main, value: "", comment: "")
}
}
2)本地化。字符串文件:
"Hi" = "Привет";
3)使用实例:
myLabel.text = "Hi".localized
享受吧!;)
——乌利希期刊指南:
对于带有注释的情况,您可以使用此解决方案:
1)扩展:
extension String {
func localized(withComment:String) -> String {
return NSLocalizedString(self, tableName: nil, bundle: Bundle.main, value: "", comment: withComment)
}
}
2) .strings文件:
/* with !!! */
"Hi" = "Привет!!!";
3)使用:
myLabel.text = "Hi".localized(withComment: "with !!!")
通过使用这种方式,可以为不同类型创建不同的实现(即Int或自定义类,如CurrencyUnit,…)也可以使用genstrings实用程序扫描这个方法调用。
只需将例程标志添加到命令中
genstrings MyCoolApp/Views/SomeView.swift -s localize -o .
扩展:
import UIKit
extension String {
public static func localize(key: String, comment: String) -> String {
return NSLocalizedString(key, comment: comment)
}
}
用法:
String.localize("foo.bar", comment: "Foo Bar Comment :)")