How to use NSLocalizedString function with variables in Swift?
You can use the sprintf
format parameters within NSLocalizedString
, so your example can look like this:
let myString = String(format: NSLocalizedString(" - %d Notifica", comment: "sottotitolo prescrizione per le notifiche al singolare"), count)
NSLocalizedString with variable in Swift
In your localisable, you can't setup a custom text directly, you can only use text and format flags. So, in order to get your goal, you can do this:
NEUEARTIKEL="Add an item to %@:";
After that, get your title well-formatted using NSString(format: <#NSString#>, <#args: CVarArgType#>...)
let title = NSString(format: NSLocalizedString("NEUEARTIKEL", nil), titelArr[sender.tag])
let alert = UIAlertController(title: title, message: nil, preferredStyle: .Alert)
Once that done, your localizable string will be formatted as you want.
NSLocalizedString With Dynamic Variable (Swift) - Not Working
Your setup isn't correct. Your code should look like this:
let localizedMsg = String(format: NSLocalizedString("I have %d dollars in my wallet.", comment: ""), countOfMoney)
Now run genstrings
to get your updated Localizable.strings file.
That will add the line:
"I have %d dollars in my wallet." = "I have %d dollars in my wallet.";
Also note the change from %@
to %d
. This assumes that countOfMoney
is an integer type. Only use %@
for object pointers.
Localized string with argument adds line breaks and brackets around argument
Please look at the output. It shows clearly that the price argument is an array. And indeed the variadic parameter args
is treated as an array.
So you are just using the wrong API
func localized(_ args: CVarArg...) -> String {
return String(format: localized, arguments: args)
}
Swift: dynamic strings with local variable injections
Totally possible /p>
You'll want to use a String initializer rather than literals.
let version = "2.0.1"
let year = 2017
let versionTemplate = String(format: NSLocalizedString("version.template", comment: ""), arguments: [version, year])
// output: Build 2.0.1, 2017
In your localizable.strings
file you need to have your template like this:
"version.template" = "Build %@, %ld"
You can use a variety of format specifiers here. Check the documentation for all the possibilities. https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html#//apple_ref/doc/uid/TP40004265-SW1
Possible to use variables and/or parameters with NSLocalizedString?
It turns out that a missing target entry is to blame. Just checking that my current build target includes the Localizable.string file solved the problem!
How to localise strings that pre-dominantly consist of variables – efficiently as dev and intuitively as translator
Thanks to Sam Deane’s Localization package provided exactly what I was after (and I believe does essentially what Larme suggested in the comment above).
public class Localization {
static var bundlesToSearch: [Bundle] = [Bundle.main]
public class func registerLocalizationBundle(_ bundle: Bundle) {
bundlesToSearch.append(bundle)
}
}
extension String {
/**
Look up a localized version of the string.
If a bundle is specified, we only search there.
If no bundle is specified, we search in a set of registered bundles.
This always includes the main bundle, but can have other bundles added to it, allowing you
to automatically pick up translations from framework bundles (without having to search through
every loaded bundle).
*/
public func localized(with args: [String:Any], tableName: String? = nil, bundle: Bundle? = nil, value: String = "", comment: String = "") -> String {
var string = self
let bundlesToSearch = bundle == nil ? Localization.bundlesToSearch : [bundle!]
for bundle in bundlesToSearch {
string = NSLocalizedString(self, tableName: tableName, bundle: bundle, value: value, comment: comment)
if string != self {
break
}
}
for (key, value) in args {
string = string.replacingOccurrences(of: "{\(key)}", with: String(describing: value))
}
return string
}
}
Thanks to the above I get exactly what I was after. Strings are defined as such in Localizable.strings:
"hourSeries_const" = "{weather} with {point} {direction} to {value} by {time}.";
And passed to the UI in code like this:
"hourSeries_const".localized(with: ["weather":"Mostly cloudy","point":"temperatures","direction":"rising","value":"24°","time":"2pm"])
Related Topics
Uitextview That Expands to Text Using Auto Layout
How to Reset the iOS Simulator from the Command Line
Xcode 6.1 Missing Required Architecture X86_64 in File
In iOS, How to Store a Secret "Key" That Will Allow Me to Communicate with My Server
In iOS, How to Drag Down to Dismiss a Modal
How to Set the Height of Tableheaderview (Uitableview) with Autolayout
iOS 13: Swift - 'Set Application Root View Controller Programmatically' Does Not Work
Uitextview - Setting Font Not Working with iOS 6 on Xcode 5
Custom Annotation View for Userlocation Not Moving the Mapview
Valid File Path for Archiverootobject and Unarchiverootobject
Xcode Without Storyboard and Arc
How to Resize Uiview by Dragging from Its Edges
How to Route Audio to Speaker Without Using Audiosessionsetproperty
How to Make a Background Image Scale to Screen Size in Swift
How to Use Subscript and Superscript in Swift
Dyld: Symbol Not Found: _Nsurlauthenticationmethodclientcertificate When Trying to Run iOS App