Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to use variables and/or parameters with NSLocalizedString?

I have tried using a variable as an input parameter to NSLocalizedString, but all I am getting back is the input parameter. What am I doing wrong? Is it possible to use a variable string value as an index for NSLocalized string?

For example, I have some strings that I want localized versions to be displayed. However, I would like to use a variable as a parameter to NSLocalizedString, instead of a constant string. Likewise, I would like to include formatting elements in the parameter for NSLocalizedString, so I would be able to retrieved a localized version of the string with the same formatting parameters. Can I do the following:

Case 1: Variable NSLocalizedstring:

NSString *varStr = @"Index1"; NSString *string1 = NSLocalizedString(varStr,@""); 

Case 2: Formatted NSLocalizedString:

NSString *string1 = [NSString stringWithFormat:NSLocalizedString(@"This is an %@",@""),@"Apple"]; 

(Please note that the variable can contain anything, not just a fixed set of strings.)

Thanks!

like image 205
futureelite7 Avatar asked Aug 10 '10 04:08

futureelite7


People also ask

What does NSLocalizedString do?

NSLocalizedString provides string localization in “compile-once / run everywhere” fashion, replacing all localized strings with their respective translation according to the string tables of the user settings.

How do I localize a string in Swift?

Select the project and under “Localizations”, click the “+” icon. Add any language you want (I selected Italian) then click on “Finish”. Now go back to Localizable. string file, select it and on the File Inspector (right menu) select “Localize”.


1 Answers

If what you want is to return the localized version of "This is an Apple/Orange/whatever", you'd want:

NSString *localizedVersion = NSLocalizedString(([NSString stringWithFormat:@"This is an %@", @"Apple"]), nil); 

(I.e., the nesting of NSLocalizedString() and [NSString stringWithFormat:] are reversed.)

If what you want is the format to be localized, but not the substituted-in value, do this:

NSString *finalString = [NSString stringWithFormat:NSLocalizedString(@"SomeFormat", nil), @"Apple"]; 

And in your Localizable.strings:

SomeFormat = "This is an %@"; 
like image 183
Wevah Avatar answered Sep 17 '22 13:09

Wevah