Home > Software design >  Using existing string from main.strings file for another element's text
Using existing string from main.strings file for another element's text

Time:09-24

I added a label (let's call it as 'newLabel') to my storyboard and added text (let's say 'Share') for it as well. I even had Localization checked for all languages in the storyboard, but still the text didn't get added to Main.strings(en) file and hence didn't get translated.

But my main.strings(en) file already has the text 'Share' which I had added for another label (let's say 'oldLabel') and that text is localized and present in main.strings file for other languages.

Is there a way where I can access that string from main.strings file and assign it to label's text property via code?

oldLabel's text in main.strings(en) file:

enter image description here

What I want to know is if something like below is possible in the code?

newLabel.text = nuq-zS-uwp.text

If yes, then how do I access nuq-zS-uwp.text in code?

CodePudding user response:

You access localized strings in code using calls to NSLocalizedString, like

let localizedShareString = NSLocalizedString("nuq-zS-uwp.text",
    value:"SHARE", 
    comment: "Share string")

That will work as long as the localized strings file from your storyboard keeps the same key, and is in the app bundle at runtime.

However, I suspect those auto-generated string key names are fragile and subject to change.

In my company we generally ignore the strings in Storyboards and replace them with strings we look up in code using NSLocalizedString().

  • Related