Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Support Dynamic Type for Multilingual Text in SwiftUI
Written by Team Kodeco

When developing a globalized application, it’s essential to accommodate not only the different languages spoken by your users but also the unique characteristics of those languages. Some languages, like Thai, require more vertical space than Latin languages. Others, like Chinese, Japanese, German and Korean, have unique conventions for text wrapping and hyphenation. To ensure your app handles these language-specific requirements, SwiftUI provides Dynamic Type.

Dynamic Type allows your app to adjust font sizes and layout attributes dynamically, ensuring readability and proper spacing no matter the language. It also adapts to user-defined text size settings, increasing accessibility.

Let’s see this in action with German, a language that requires significantly more vertical space for certain characters. You’ll create a view that displays an English sentence and its German equivalent. You’ll then use a Slider to adjust the text size dynamically.

struct ContentView: View {
  @State private var textSize: CGFloat = 16

  var body: some View {
    VStack(spacing: 20) {
      Slider(value: $textSize, in: 16...40, step: 1)
        .padding()
        .labelsHidden()
      Text("A small black cat climbs a tall tree, looking around for prey")
        .font(.system(size: textSize))
        .padding()
      Text("Eine kleine schwarze Katze klettert auf einen hohen Baum und sucht nach Beute")
        .font(.system(size: textSize))
        .padding()
      Spacer()
    }.padding()
  }
}

Here’s what your preview should look like:

Preview of the Dynamic Type in SwiftUI.
Preview of the Dynamic Type in SwiftUI.

Notice how the German text requires more vertical space than the English text.

In this example, you use a Slider to adjust the textSize state variable, which controls the font size of both the English and German text. As you adjust the slider, notice how SwiftUI handles text wrapping and vertical spacing for both languages. This adaptive behavior of SwiftUI, facilitated by Dynamic Type, helps ensure that your app’s typography is clear and readable, regardless of the language or script it’s displayed in.

In summary, supporting languages that require different text dimensions and layouts is an important aspect of internationalizing your SwiftUI app. Dynamic Type is an excellent tool that can help you achieve this, enhancing your app’s readability and accessibility for users worldwide.

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.