Home > OS >  SwiftUI - localized accessibility label
SwiftUI - localized accessibility label

Time:03-16

I have the following code in SwiftUI and I want to translate accessibility label from English to Polish:

Text("Example")
.accessibilityLabel("Color: \(color.description)")

And I have such translations in Localizable.strings file:

/* Color: color.description */
"Color: %@" = "Kolor: %@";

/* Color */
"blue" = "niebieski";

I've tested this with VoiceOver and it reads: "Kolor: blue" But should read: "Kolor: niebieski"

Which means that color.description ("blue" in my case) wasn't translated to "niebieski". Why is that? What am I doing wrong?

CodePudding user response:

You should use the NSLocalizedString to localize your string.

So In your case you should be using

Text("Example")
.accessibilityLabel(String(format: NSLocalizedString("Color: %@", comment: ""),
 color.description))

CodePudding user response:

I fixed it :) It's quite simple.

Here is a working code:

Text("Example")
  .accessibilityLabel("Color")
  .accessibilityValue(LocalizedStringKey(Color.blue.description))

And if color value is from a variable (like in the original question), it will be:

Text("Example")
  .accessibilityLabel("Color")
  .accessibilityValue(LocalizedStringKey(color.description))

What is important is to use localizedString(value:). And I've separated accessibilityLabel to separate accessibilityLabel and accessibilityValue.

  • Related