NSLocalizedString with variables Swift

后端 未结 5 1438
北海茫月
北海茫月 2020-12-30 00:17

I\'m trying to figure out how to use NSLocalizedString with variables.

For example, if I want to output \"by Peter and Larry\", in my Localizable.strings

相关标签:
5条回答
  • 2020-12-30 00:46

    An example with the Localizable.strings file:

    In Localizable.strings file:

    localizable_text = "Title %@ (Code: %@)";
    

    In Swift class:

    let title = "Error"
    let code = "123456"
    let alertMessage = String(format: NSLocalizedString("localizable_text", comment: ""), title, code)
    
    0 讨论(0)
  • 2020-12-30 00:47

    yes, you should have "account.by_user" = "by %@ and %@"; and take this:

    let localizedString = NSLocalizedString("account.by_user", comment: "any comment")
    let wantedString = String(format: localizedString, "Peter","Larry")
    
    0 讨论(0)
  • 2020-12-30 00:50
    String(format: NSLocalizedString("Pick_Only", comment: ""), sectionData.max)
    

    In Localizable.strings: "Pick_Only" = "Pick only %d";

    0 讨论(0)
  • 2020-12-30 00:57

    This is another way and how I do it.

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

    basically, the main idea of Localized String with format is like this:

    let math = "Math"
    let science = "Science"
    String.localizedStringWithFormat(NSLocalizedString("I love %@ and %@", comment: "loved Subjects"), math, science)
    
    0 讨论(0)
  • 2020-12-30 01:01

    Adding a small sample below as it took me some time to figure the Localizable.strings file formatting.

    Example of adding variables to localized string:

    In code:

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

    In Localizable.strings file:

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

    Of course, the %@ on the right side can be replaced:

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

    Also, %@ can be replaced by %d for int or %f for a float.

    0 讨论(0)
提交回复
热议问题