How to localize a string with formatting placeholders?
-
18-06-2021 - |
Question
I need to translate text in controller.body
My code:
controller.body = [NSString stringWithFormat:@"\n\n"
"Label 1: %@ \n"
"Label 2: %@ \n"
"Label 3: %@ \n"
"Label 4: %@", label1.text, label2.text, label3.text, label4.text];
I have file Localizable.strings, how can I localize a string with formatting placeholders? I mean that text "Label 1", "Label 2" etc...
Solution
You will need to use NSLocalizedString
your localizable.string
will look like
"Label 1: %@ \n" = "your label";
"Label 2: %@ \n" = "your label";
//And so on...
And your code
controller.body = [NSString stringWithFormat:@"\n\n",
NSLocalizedString(@"Label 1: %@ \n", nil),
NSLocalizedString(@"Label 2: %@ \n", nil),
etc....];
OTHER TIPS
Something this for localize string
controller.body = [NSString stringWithFormat:NSLocalizedString(@"Label 1: %@ ," , @"Label 2: %@ ,", @"Label 3: %@ ," , @"Label 4: %@ ,"), label1.text,label2.text,label3.text,label4.text]
The pattern:
NSString* stringFormat = NSLocalizedString (@"LabelStringFormat", ...);
NSString* labelText = [NSString stringWithFormat:stringFormat, label1.text, ...];
and in your localised.strings
"LabelStringFormat" = "Label 1: %@, ...";
You can even re-order the items without code by using the right string format.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow