Yasir TIRAK
Yasir TIRAK

Reputation: 13

How can I localise my multiple string in swift?

When I do as below, I can write all string expressions in different languages. But it doesn't happen when I make a multi line String. Please help me on how to Integrate this?

Modal

Unit(unit: "Unit 1".localized(),
             category: [Category(category: "Personal Pronouns".localized()])

controller

extension String {
    func localized() -> String {
        return NSLocalizedString(self,
                                 tableName: "Localizable",
                                 bundle: .main,
                                 value: self,
                                 comment: self)
    }      
}

localizable.string

"Unit 1" = "Unité 1";
"Personal Pronouns" = "Pronoms personnel";

The multi line string I want to do will be like this but how ?

let text = """
    We want to change the World
    but not everywhere or everything
    only on people 
        """

https://github.com/ysrtirak/Make-localise here there is my example

I could not translate the text in """ """

Upvotes: 0

Views: 669

Answers (1)

Duncan C
Duncan C

Reputation: 131408

I haven't tried it, but according to this SO answer you can put multi-line strings directly into your localizable.strings file:

localizable.strings:

"multiLine" = "We want to change the World
but not everywhere or everything
only on people";

And in your swift code:

print("multiLine".localized())

I just tried a test application, and the following localizable.strings file worked perfectly:

/* 
  Localizable.strings
  MultiLine

  Created by Duncan Champney on 8/13/21.
  
*/
"foo" = "This
is
a
multi-line
string";

With that localizable.strings file, this code:

        print(NSLocalizedString("foo", value: "foo", comment: "comment"))

prints the output:

This
is
a
multi-line
string

Just as you would expect it to.

Edit:

Try downloading this sample app from Github. It is a working example of using multi-line strings in a localizable.strings file.

Edit #2:

You have an extra newline at the beginning and end of the English in your French localizable.strings. Change it as follows:

/* 
  Localizable.strings
  Make localise

  Created by Yasir Tırak on 15.08.2021.
  
*/

"I know how to localise that . thats not problem" = "Je sais comment localiser ça. ce n'est pas un problème";
"This is my text
But i cant localise it
hey
how are you" = "C'est mon texte
Mais je ne peux pas le localiser
Hé
Comment ça va";

That works.

To figure out what was going on, I broke your code into steps and logged the results:

 let text = """
 This is my text
 But i cant localise it
 hey
 how are you
 """
 print("text = '\(text)'")
 let localizedText = text.localized()
 textLabel.text = localizedText

That outputs:

text = 'This is my text
But i cant localise it
hey
how are you'

Note how there are no newlines before the first single quote and none after the last single quote.

Upvotes: 2

Related Questions