wangshaoping
wangshaoping

Reputation: 83

Localizable.strings key-value pair

I want to localize "1 of 9", and 1 and 9 are int parameters, my code is as below

context = [NSString stringWithFormat:NSLocalizedString(@"%d of %d", 
          "This text will be used to show page number on the screen"), 
          currentPageIndex + 1, pageCount];

And the generated Localizable.strings show like that

/* This text will be used to show page number on the screen */
"%d of %d" = "%1$d of %2$d";

I think the thing on the left of "=" is key and the the thing on the right of "=" is value, but I want the key looks like "show_page_number" not included the format "%d", how can I do? I try to replace "%d of %d" with "show_page_number", but it does not work. Any advice?

Upvotes: 0

Views: 1702

Answers (2)

Ellen
Ellen

Reputation: 5190

NSLocalizedString() replaced key with value at runtime .So you can use anystring as key & it will be replaced as "%1$d of %2$d" at runtime. Add string in Localizable file :

"show_page_number" = "%1$d of %2$d";

& in code use that key

context = [NSString stringWithFormat:NSLocalizedString(@"show_page_number", "This text will be used to show page number on the screen"), currentPageIndex + 1, pageCount];

Add localizable.string file in xcode project.

EDIT

Upvotes: 1

rmaddy
rmaddy

Reputation: 318774

If you want full control over the key and its initial value you need to use NSLocalizedStringWithDefaultValue instead of NSLocalizedString (which uses the key as the initial value).

Change your code to:

NSString *format = NSLocalizedStringWithDefaultValue(@"show_page_number", @"Localizable", NSBundle.mainBundle, @"%1$d of %2$d", @"This text will be used to show page number on the screen")
context = [NSString stringWithFormat:format, currentPageIndex + 1, pageCount];

When you run genstrings, you will get:

/* This text will be used to show page number on the screen */
"show_page_number" = "%1$d of %2$d";

Upvotes: 1

Related Questions