Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Localize a Date in SwiftUI
Written by Team Kodeco

Localization is vital for an application aiming for a global audience. It ensures the inclusivity of different language-speaking users, hence enhancing user experience. SwiftUI provides straightforward tools to facilitate localization. In this cookbook entry, you will walk through how to display the date in SwiftUI and change its language programmatically.

In the following example, you’ll create a view that displays the current date and time and offers the user a selection of languages to choose from. You’ll use SwiftUI’s Picker view to create a language selector, and the environment modifier to change the display language of the date.

struct ContentView: View {
  let now = Date()
  let languages = ["en", "fr", "es", "de", "zh"]
  @State private var selectedLanguage = "en"

  var body: some View {
    VStack {
      Picker("Language", selection: $selectedLanguage) {
        ForEach(languages, id: \.self) { language in
          Text(language.uppercased()).tag(language)
        }
      }
      .pickerStyle(SegmentedPickerStyle())
      .padding()

      HStack {
        Text(now, style: .date)
        Spacer()
        Text(now, style: .time)
      }
      .environment(\.locale, Locale(identifier: selectedLanguage))
      .padding()
    }
  }
}

Here’s what your preview should look like:

Localize a date in SwiftUI.
Localize a date in SwiftUI.

In this example, now is a constant that represents the current date and time. You declare an array languages containing the language codes of the languages you want to support.

A Picker view is set up, allowing the user to select a language from the list. The SegmentedPickerStyle provides a neat, segmented control to switch between languages.

Finally, you have an HStack containing two Text views that display the current date and time. These views use the environment modifier to update the locale according to the language currently selected by the user. Locale(identifier: selectedLanguage) changes the language in which the date and time are displayed, according to the user’s selection. The main takeaway to notice is that by adding the style parameter to Text SwiftUI will take care of the localization for us automatically. Cool huh?

So, by utilizing SwiftUI’s Picker view and environment modifier, you can easily create a view that displays the date and allows the user to change its language programmatically. This is a simple yet powerful way to enhance the user experience in your application, especially for global users.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.