Responding to Dynamic Type in SwiftUI for Accessibility
Written by Team Kodeco
Ensuring that our applications are accessible to all users, including those with visual impairments, is a vital aspect of modern app development. One essential feature to support is Dynamic Type, which allows users to adjust the text size across all apps for improved readability. This recipe will show you how to handle Dynamic Type in your SwiftUI application.
By default, SwiftUI’s Text view automatically adjusts its font size according to the user’s Dynamic Type setting, provided you have not explicitly set a fixed font size. Here’s a simple example:
struct ContentView: View {
var body: some View {
Text("Hello, World!")
}
}
In this case, the text “Hello, World!” will adjust its size according to the user’s preference set in the iOS Settings.
If your app needs to respond to changes in the Dynamic Type setting in real-time (for example, to adjust the layout), you can monitor the current size category using the @Environment(\.sizeCategory)
property wrapper. This gives you an ContentSizeCategory
value that you can use:
struct ContentView: View {
@Environment(\.sizeCategory) var sizeCategory
var body: some View {
VStack {
if sizeCategory >= .accessibilityMedium {
Text("You have selected a larger text size.")
.padding()
} else {
Text("The text size is set to a regular value.")
.padding()
}
}
}
}
Turn on Dynamic Text in your preview and update the text size to AX 3 and you should see the following:
In this example, you use sizeCategory
to adjust the layout based on the user’s Dynamic Type setting.
By handling Dynamic Type in your app, you ensure that users with visual impairments can read and interact with your content more easily, creating a more inclusive user experience.