Skip to content
DeveloperMemos

Localizing Text in Custom SwiftUI Views with LocalizedStringKey

SwiftUI, LocalizedStringKey, Localization, Custom Views1 min read

When building localized SwiftUI apps, LocalizedStringKey is your trusty companion. It allows you to look up localized strings, making your app accessible to users around the world. In this article, we'll dive into how you can leverage LocalizedStringKey within your own custom views.

1. Implicit Localization

Several SwiftUI types implicitly look up a localized string when you provide a string literal. For example, when you create a Text("Hello"), SwiftUI automatically creates a LocalizedStringKey for you and uses it to look up the localized version of the "Hello" string.

2. Creating a LocalizedStringKey

Here's how you can create a LocalizedStringKey explicitly:

1let localizedStringKey: LocalizedStringKey = "Hello"

If you have a string variable (e.g., user-provided input), you can avoid localization by passing it directly to the initializer. Use a string literal argument when you want localization and a string variable argument when you don't.

3. Example: Custom View

Suppose you're building a weather app, and you want to display the current weather condition. Let's create a custom view called WeatherConditionView:

1struct WeatherConditionView: View {
2 let condition: String // e.g., "Sunny", "Rainy", etc.
3
4 var body: some View {
5 VStack {
6 Text("Current Weather:")
7 .font(.headline)
8 Text(condition) // Uses the string value verbatim
9 .font(.subheadline)
10 }
11 }
12}

In this example, we're displaying the weather condition directly from the condition variable. If you want to localize the weather conditions, create a new LocalizedStringKey instance from the string:

1struct WeatherConditionView: View {
2 let condition: String // e.g., "Sunny", "Rainy", etc.
3
4 var body: some View {
5 VStack {
6 Text("Current Weather:")
7 .font(.headline)
8 Text(LocalizedStringKey(condition)) // Localized version
9 .font(.subheadline)
10 }
11 }
12}

Now you're ready to create custom views that adapt to different languages seamlessly. Happy localizing! 🌎🌍🌏