NSLocalizedString and value with SwiftUI

1.1k views Asked by At

I'm trying to localize a Text view with a value inside without success!

Here's what I'm usually do:

// ContentView.swift

Text("Tomato")
/* replaced by */
Text(NSLocalizedString("text-tomato", comment: ""))

// Localizable.strings (en)

"text-tomato" = "Tomato";

But with a value inside I don't know how to proceed:

// ContentView.swift

Text("3 Tomatoes")
/* or */
Text("\(tomatoes.count) Tomatoes")
/* replaced by */
Text(NSLocalizedString("\(tomatoes.count) text-tomatoes", comment: ""))

// Localizable.strings (en)

"%@ text-tomatoes" = "%@ Tomatoes";
/* or maybe */
"(tomatoes.count) text-tomatoes" = "%@ Tomatoes";
/* or maybe */
"%@ text-tomatoes" = "(tomatoes.count) Tomatoes";

I have tried to use %@, %lld, value, etc without success. Do you have any idea?

3

There are 3 answers

0
Alexnnd On BEST ANSWER

I have finally found an answer right after posting my question:

// ContentView.swift

Text("3 Tomatoes")
/* or */
Text("\(tomatoes.count) Tomatoes")
/* replaced by */
Text(String(format: NSLocalizedString("%lld text-tomatoes", comment: ""), tomatoes.count))

// Localizable.strings (en)

"%lld text-tomatoes" = "%lld Tomatoes";

It's working like a charm!

Other example: Localization with String interpolation in SwiftUI

1
Esteban Rafael Trivino Guerra On

Thank you @Alexxnd

This is what worked for me:

let notAllowedChar = String(format: NSLocalizedString("TextfieldNotAllowedChar %@", comment: ""), char)

"TextfieldNotAllowedChar %@" -> "No permitido el character '%@'"


I was having trouble with:

SwiftUI.LocalizedStringKey.FormatArgument(storage: SwiftUI.LocalizedStringKey.FormatArgument.Storage.value( ...
0
Yurkevich On

You should not use NSLocalisedString with SwiftUI, use normal Text():

Text("Tomatoes", comment: "TODO item")

Text("\(viewModel.tomatoesCount, specifier: "%lld") Tomatoes",
    comment: "TODO item with number")

Do not ignore comments, it will help with context during translation.

Read more at Preparing views for localization