0

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?

Alexnnd
  • 429
  • 4
  • 13
  • Look at this https://stackoverflow.com/a/62042837/12299030, https://stackoverflow.com/a/60342131/12299030, https://stackoverflow.com/a/61383558/12299030, https://stackoverflow.com/a/65187817/12299030, and https://stackoverflow.com/a/65623431/12299030 for different examples – Asperi Jun 02 '22 at 16:50

3 Answers3

1

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

Boris Y.
  • 4,387
  • 2
  • 32
  • 50
0

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

Alexnnd
  • 429
  • 4
  • 13
0

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( ...
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Vikram Parimi Sep 07 '22 at 12:15