我想在swift应用程序中为集合视图添加一个本地化字符串数组作为数据源。
我写了这个:
let text = [NSLocalizedString("s0",comment: ""),NSLocalizedString("s1",comment: ""),NSLocalizedString("s2",comment: ""),NSLocalizedString("s3",comment: ""),NSLocalizedString("s4",comment: ""),NSLocalizedString("s5",comment: ""),NSLocalizedString("s6",comment: ""),NSLocalizedString("s7",comment: ""),NSLocalizedString("s8",comment: "")]
是否有更简单的方法将所有字符串放入数组中,因为我有1000个本地化字符串,这看起来不正确。
答案 0 :(得分:1)
您始终可以使用格式(例如s%d.4)设置字符串,并围绕该格式构建数组。
var text:NSMutableArray = NSMutableArray()
for index in 1...10 {
let formattedString = String(format: "s%.4d", index)
let localizedString = NSLocalizedString(formattedString, comment: "comment")
text.addObject(localizedString)
}
然后你声明你的字符串:s0001,s0002,s0003等
答案 1 :(得分:0)
或者,您也可以那样做:
HelperClass :
static func getLocalized(withKey key: String, targetSpecific:Bool) -> String{
if targetSpecific{
return NSLocalizedString(key, tableName:"TargetSpecific", comment: "")
}
else{
return NSLocalizedString(key, comment: "")
}
}
static func getLocalizedArray(withKey key: String, targetSpecific:Bool) -> [String]{
return getLocalized(withKey: key, targetSpecific: targetSpecific).components(separatedBy: ",")
}
Localizable.string
"optionsArray" = "Show devices,Add device";
因此您可以这样称呼它:
let optionsArray:[String] = AppHelper.getLocalizedArray(withKey: "optionsArray", targetSpecific: false)
答案 2 :(得分:0)
编辑:意识到您可以分两步而不是三步编写。简化了我的答案。
public func Localized(_ key: String) -> String {
return NSLocalizedString(key, comment: "")
}
// for example
let localized = ["s0", "s1", "s2"].map { Localized($0) }