How can I localise my multiple string in swift? - ios

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 """ """

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.

Related

Swift localizedStringWithFormat number output instead of Text

Currently I am working on a Localization for my App. When I want to logout the user, I want to tell his name in the alert. So I used the following code:
let name = "Matthias Kremer"
let formatedString = NSLocalizedString("logoutTitleWithName", comment: " abmelden?")
print( String.localizedStringWithFormat(formatedString, name))
The Localizable.string file looks like that:
"logoutTitleWithName" = "%d abmelden";
I supposed to get the following outlet:
Matthias Kremer abmelden
But instead it is
281,600 abmelden
It seams like the String is converted in a Number somehow. Does anybody knows how to deal with this?
Change
"logoutTitleWithName" = "%# abmelden";
%d is a repacement for decimal value while %# for a string

Case Insensitive Localization in iOS

While implementing localization I realize that localization is case sensitive, what means:
- "Cookie Selection" = "Sélection de biscuit";
- "COOKIE SELECTION" = "SÉLECTION DE BISCUIT";
above two are different entities. If you localize like NSLocalizedString("cookie selection", comment: ""), this will not get localized as the key value mapping given for "cookie selection" is either for capitalized string or for Uppercased string.
Query:
If I can make it case insensitive, in the sense like I will add only one pair for localization as
"Cookie Selection" = "Sélection de biscuit";
and this should work for all cases like below
1. NSLocalizedString("Cookie Selection", comment: "")
2. NSLocalizedString("COOKIE SELECTION", comment: "")
3. NSLocalizedString("cookie selection", comment: "")
Note: -> without any custom method, use only NSLocalization.
Happy Coding
Nope....Better use a constant file where you will store all the localization constants and its values so by mistake localization constant value does not change by mistake(suppose you type cookie Selection instead of Cookie Selection) while calling. You will use then values in localizable files as key.
LocalizationConstants.swift
let CookieSelectionKey = "Cookie Selection"
Localizable.strings(English)
"Cookie Selection" = "Selection Of cookie";
Now call it like
NSLocalizedString(CookieSelectionKey, comment: "")
Since it returns a string you can use string instance methods such as uppercased, capitalized(etc.) to change case accordingly.
You could always remove the possibility of getting it wrong by making a struct to encapsulate your localised logic etc...
enum Strings: String {
case cookieSelection
var localized: String {
return NSLocalizedString(self.rawValue, comment: "Something here")
}
}
With something like this you can now keep track of all your localised strings in one place and also remove any chance of them being used incorrectly.
For usage do something like...
label.text = Strings.cookieSelection.localized
If you want a default value for the string you can add that to the case...
enum Strings: String {
case cookieSelection = "Cookie Selection"
}
The simplest and most raw solution would be to always capitalize the key like so:
NSLocalizedString("cookie selection".uppercased(), comment: "Comment")
More cleaner approach would be to create a category on String class and use that method instead:
extension String {
public static func LocalizedString(key: String, comment: String) -> String {
return NSLocalizedString(key.uppercased(), comment: comment)
}
}
// Usage
String.LocalizedString(key: "cookie selection", comment: "")
Another nice approach would be to make a file of constants and use them instead of using hard coded strings.

Swift localization with possessive

I'm dabbling with localization in Swift. It's been pretty straightforward until I have to deal with possessive.
Say I have these phrases in English:
Carol's car is red.
Kris' car is red.
In French, they would be
La voiture de Carol est rouge
La voiture de Kris est rouge
How would I set up my Localizable.strings (French) file? I'd imagine it's something like:
"key" = "La voiture de %# est rouge";
But this doesn't really work.
Yes, you can replace text with you required value. I have just using your flow of questions, so answer is same it is.
First create your localized string as follow:
"key" = "La voiture de #name# est rouge";
Then, when you required your string. i.e
let strFrench = Localizable.strings(French)
Localizable.strings(French), this is you are assuming, so I have wrote this.
Now replace name with your dynamic value as follow:
let str = strFrench.replacingOccurrences(of: “#name#”, with: “YourString”)
I hope this will work for you. Sorry for my bad English.
Try this method..
First you declare language bundle globally like as below
var languageBundle:Bundle?
then you set path for your language ,
if let path = Bundle.main.path(forResource: "Fr", ofType: "lproj") {
languageBundle = Bundle(path: path)
} else {
languageBundle = Bundle(path: Bundle.main.path(forResource: "Base", ofType: "lproj")!)
}
then you assign the key name to your label
labelTerms.text = ((languageBundle?.localizedString(forKey: "labelAcceptTerms", value: "", table: nil) as String!))
Thats all!!
Before you proceed please confirm you followed below steps for creating localized string file
Select project —> Select Use base Internationalization — > add language —> Goto storyboard and add select the checkbox (New languages added) — > add a string file localized.string —> add list of strings in that --> Use the key name .localizedString(forKey:"addyourkeyname"

Unable to use localizable strings

I am trying to follow all instructions I have found in previous questions in term of localizing the application.
I Have succeeded in localizing storybaord when strings were generated. Now I am trying to prepare .strings file in order to use them in my swift files.
what I did:
new -> file -> strings file
Create localization of at least 2 languages on the previously created .strings file
I have put values in (polish)
"HELLO_WORLD" = "Dzień dobry!";
and in (english)
"HELLO_WORLD" = "Hello world!";
I have created string extension as follows:
extension String {
var localized: String {
return NSLocalizedString(self, tableName: nil, bundle: Bundle.main, value: "", comment: "")
}
}
I am trying to show the value like:
`helloworldLabel.text = "HELLO_WORLD".localized
but everything I gets is the same result. In hello world label I see "HELLO_WORLD"
can anyone give me a hint what Am I doing wrong?

How to capitalize each word in a string using Swift iOS

Is there a function to capitalize each word in a string or is this a manual process?
For e.g. "bob is tall"
And I would like "Bob Is Tall"
Surely there is something and none of the Swift IOS answers I have found seemed to cover this.
Are you looking for capitalizedString
Discussion
A string with the first character in each word changed to its corresponding uppercase value, and all remaining characters set to their corresponding lowercase values.
and/or capitalizedStringWithLocale(_:)
Returns a capitalized representation of the receiver using the specified locale.
For strings presented to users, pass the current locale ([NSLocale currentLocale]). To use the system locale, pass nil.
Swift 3:
var lowercased = "hello there"
var stringCapitalized = lowercased.capitalized
//prints: "Hello There"
Since iOS 9 a localised capitalization function is available as capitalised letters may differ in languages.
if #available(iOS 9.0, *) {
"istanbul".localizedCapitalizedString
// In Turkish: "İstanbul"
}
An example of the answer provided above.
var sentenceToCap = "this is a sentence."
println(sentenceToCap.capitalizedStringWithLocale(NSLocale.currentLocale()) )
End result is a string "This Is A Sentence"
For Swift 3 it has been changed to capitalized .
Discussion
This property performs the canonical (non-localized) mapping. It is suitable for programming operations that require stable results not depending on the current locale.
A capitalized string is a string with the first character in each word changed to its corresponding uppercase value, and all remaining characters set to their corresponding lowercase values. A “word” is any sequence of characters delimited by spaces, tabs, or line terminators (listed under getLineStart(_:end:contentsEnd:for:)). Some common word delimiting punctuation isn’t considered, so this property may not generally produce the desired results for multiword strings.
Case transformations aren’t guaranteed to be symmetrical or to produce strings of the same lengths as the originals. See lowercased for an example.
There is a built in function for that
nameOfString.capitalizedString
This will capitalize every word of string. To capitalize only the first letter you can use:
nameOfString.replaceRange(nameOfString.startIndex...nameOfString.startIndex, with: String(nameOfString[nameOfString.startIndex]).capitalizedString)
Older Thread
Here is what I came up with that seems to work but I am open to anything that is better.
func firstCharacterUpperCase(sentenceToCap:String) -> String {
//break it into an array by delimiting the sentence using a space
var breakupSentence = sentenceToCap.componentsSeparatedByString(" ")
var newSentence = ""
//Loop the array and concatinate the capitalized word into a variable.
for wordInSentence in breakupSentence {
newSentence = "\(newSentence) \(wordInSentence.capitalizedString)"
}
// send it back up.
return newSentence
}
or if I want to use this as an extension of the string class.
extension String {
var capitalizeEachWord:String {
//break it into an array by delimiting the sentence using a space
var breakupSentence = self.componentsSeparatedByString(" ")
var newSentence = ""
//Loop the array and concatinate the capitalized word into a variable.
for wordInSentence in breakupSentence {
newSentence = "\(newSentence) \(wordInSentence.capitalizedString)"
}
// send it back up.
return newSentence
}
}
Again, anything better is welcome.
Swift 5 version of Christopher Wade's answer
let str = "my string"
let result = str.capitalized(with: NSLocale.current)
print(result) // prints My String

Resources