2016-03-15 52 views
2

我想翻譯一個字符串,裏面有兩個變量。 的那一刻,我使用這個翻譯代碼:2個變量和不同語言的快速文本

NSLocalizedString("Name_In_Langauge_String_File",comment:"") 

但我怎麼能翻譯下面的字符串?

這與100頁的圖片和50個用戶

其中100和50是變量的測試。

+1

[nslocalizedstring with swift variable](http://stackoverflow.com/questions/26277626/nslocalizedstring-with-swift-variable) –

+0

是的,我也發現了這個,但怎麼做它看起來像Localizable.string? – Stack108

+0

[字符串格式swift](https://thatthinginswift.com/string-formatting/) –

回答

2

在您Localizable.strings將這個:

"Name_In_Langauge_String_File" = "This is a test with %d Pictures and %d Users"; 

並在代碼:

String.localizedStringWithFormat(
    NSLocalizedString("Name_In_Langauge_String_File", 
    comment: ""), 
    pictures, 
    users) 
+0

非常感謝! :) – Stack108

0

在一個項目我工作,我注意到,我們不停地重複代碼來執行字符串格式化本地化文件。這意味着您不能僅僅使用該值,您首先需要檢查需要的參數。避免這個問題的一個方法是使用Swift枚舉。此方法對於單元測試您的本地化也很有用。

假設你已經在你的字符串以下3個本地化文件:

"TestNoParams" = "This is a test message"; 
"TestOneParam" = "Hello %@"; 
"TestTwoParams" = "This is a test with %d Pictures and %d Users"; 

現在你可以使用下面的枚舉,協議和擴展引用您的字符串:

protocol LocalizationProtocol { 
    var key: String { get } 
    var value: String { get } 
} 

extension LocalizationProtocol { 
    private func localizationValue() -> String { 
     return NSLocalizedString(key, comment:key) 
    } 

    private func localizationValueWithFormat(parameters: CVarArgType...) -> String { 
     return String(format: localizationValue(), arguments: parameters) 
    } 
} 

enum Localizations: LocalizationProtocol { 
    case TestNoParams 
    case TestOneParam(name: String) 
    case TestPicturesAndUsers(pictures: Int, users: Int) 

    var key: String { 
     switch self { 
     case .TestNoParams: return "TestNoParams" 
     case .TestOneParam: return "TestOneParam" 
     case .TestPicturesAndUsers: return "TestTwoParams" 
     } 
    } 

    var value: String { 
     switch self { 
     case .TestOneParam(let name): 
      return localizationValueWithFormat(name) 

     case .TestPicturesAndUsers(let pictures, let users): 
      return localizationValueWithFormat(pictures, users) 

     default: 
      return localizationValue() 
     } 
    } 
} 

我們使用它您只需要調用枚舉值方法:

let testNoParam = Localizations.TestNoParams.value 
let testOneParam = Localizations.TestOneParam(name: "users name").value 
let testTwoParams = Localizations.TestPicturesAndUsers(pictures: 4, users: 500).value 

示例I hav e顯示簡化,但您也可以嵌套枚舉爲您的本地化提供一個很好的分組。例如,你可以讓你的枚舉由ViewController嵌套。這是一個歡迎消息的例子:Localizations.Main.WelcomeMessage.value