Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSLocalizedString with variable in Swift

How can I translate a string that has a variable in it like this:

let alert = UIAlertController(title: NSLocalizedString("NEUEARTIKEL",comment:"Bitte gib einen neuen Artikel für \(titelArr[sender.tag]) an:"), message: nil, preferredStyle: .Alert)

When I just translate the String normally like this in the localizable.string:

NEUEARTIKEL="Add an item to \(titelArr[sender.tag]):";

The alert will show (titelArr[sender.tag]) instead of its value.

This is probably very simple, but I`m new to swift an wasn't able to google something helpful! ;-)

Thanks for your help //Seb

like image 353
Seb Avatar asked Mar 14 '26 02:03

Seb


1 Answers

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.

like image 188
tbaranes Avatar answered Mar 16 '26 16:03

tbaranes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!