How do I localize a string with formatting placeholders?
How do I localize a string that has placeholders in it with NSLocalizedString?
[NSString stringWithFormat:@"You can afford %i at %@%li.",[kCash integerValue]/self.price, kYen, self.price]
How do I localize this? Do I do break up the strings into multiple localized strings? How then do I deal with varying sentence structure and grammar?
4 Solutions Collect From Internet About “How do I localize a string with formatting placeholders?”
Have the localized strings include the placeholders. That’s pretty much the only proper way to do it as otherwise, as you mentioned, you couldn’t take varying word order into account.
Something along these lines:
[NSString stringWithFormat:NSLocalizedString(@"Foo %i", @"Foo %i"), 123]
NSLocalizedString won’t alter your placeholders, so stringWithFormat can use them as normal. In your example, using numbered placeholders is probably a good idea –
[NSString stringWithFormat:@"You can afford %1$i at %2$@%3$li.", [kCash integerValue]/self.price, kYen, self.price]
More info here:
Is there a way to specify argument position/index in NSString stringWithFormat?
Another approach to this is in your localized file, you can have:
key = "String with %@ placeholder";
and in your implementation:
[NSString stringWithFormat: NSLocalizedString(@"key", ""), @"string replacing placeholder"];
You can do this with any number of arguments, they just need to be consistent across your localization files.
This way seems more efficient:
[NSString stringWithFormat:@"%@ %@", NSLocalizedString(@"Key", @"Comment for localised string"), value];
- Creating an NSCache for the first time with CloudKit Records – close?
- Share Extension is not working in Chrome
- iOS7 and Apple Watch
- UIView dynamic height depending on Label Height
- ios: how to dismiss a modal view controller and then pop a pushed view controller
- Remove multiple components in react native
- Error: _handleNonLaunchSpecificActions in iOS9
- How to resume background audio in Swift 2 / AVPlayer?
- how does one check if UIWebView is empty or not
- iOS 7 UITextView vertical alignment
- Custom font in a storyboard?
- How to convert code objective c to Swift to save image?
- UISearchBarController iOS 11 issue – SearchBar and scope buttons overlap
- Undefined symbols for architecture arm64
- Changing icon of package created by package maker