Peter Warbo
Peter Warbo

Reputation: 11728

NSLocalizedString with format

How would I use NSLocalizedString for this string:

[NSString stringWithFormat:@"Is “%@“ still correct for “%@“ tap “OK“ otherwise tap “Change“ to choose new contact details", individual.contactInfo, individual.name];

When using stringWithFormat before I've used it in the following manner:

[NSString stringWithFormat:@"%d %@", itemCount, NSLocalizedString(@"number of items", nil)];

Upvotes: 42

Views: 26037

Answers (4)

Peter Kreinz
Peter Kreinz

Reputation: 8686

Swift

//Localizable.strings

"my-localized-string" = "foo %@ baz";

Example:

myLabel.text = String(format: NSLocalizedString("my-localized-string", 
                                       comment: "foo %@ baz"), "bar") //foo bar baz

Upvotes: 3

Alexander
Alexander

Reputation: 7238

I just want to add one very helpful definition which I use in many of my projects.

I've added this function to my header prefix file:

#define NSLocalizedFormatString(fmt, ...) [NSString stringWithFormat:NSLocalizedString(fmt, nil), __VA_ARGS__]

This allows you to define a localized string like the following:

 "ExampleScreenAuthorizationDescriptionLbl"= "I authorize the payment of %@ to %@.";

and it can be used via:

self.labelAuthorizationText.text = NSLocalizedFormatString(@"ExampleScreenAuthorizationDescriptionLbl", self.formattedAmount, self.companyQualifier);

Upvotes: 13

trojanfoe
trojanfoe

Reputation: 122458

Given sentences can be constructed with the variable parts in a different order in some languages then I think you should use positional arguments with [NSString stringWithFormat:]:

NSString *format = NSLocalizedString(@"number_of_items", @"Number of items");

Which would load the following string for English:

@"Is \"%1$@\" still correct for \"%2$@\" tap \"OK\" otherwise tap \"Change\" to choose new contact details"

And perhaps something else for French (I don't know French so I won't attempt a translation, but it could well have the first and second argument in a different order):

"French \"%2$@\" french \"%1$@\" french"

And you can safely format the string as normal:

NSString *translated = [NSString stringWithFormat:format individual.contactInfo, individual.name];

Upvotes: 34

Hot Licks
Hot Licks

Reputation: 47759

[NSString stringWithFormat:NSLocalizedString(@"Is “%@“ still correct for “%@“ tap “OK“ otherwise tap “Change“ to choose new contact details", @"Query if parm 1 is still correct for parm 2"), individual.contactInfo, individual.name];

Upvotes: 75

Related Questions