2

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

2

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

Comments

6

This is another way and how I do it.

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

basically, the main idea of Localized String with format is like this:

let math = "Math"
let science = "Science"
String.localizedStringWithFormat(NSLocalizedString("I love %@ and %@", comment: "loved Subjects"), math, science)

Comments

1
let myString = String(format: NSLocalizedString("account.by_user", comment: "any comment"), "Peter","Larry")

let title = String(format:
            NSLocalizedString("account.user_count", comment: ""),
                           users.count.description)

You can find gist here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.