Using the New iOS 15 DynamicTypeSize in SwiftUI | by Rudrank Riyam | Mar, 2022

Make your text and views accessible for different font sizes

Rudrank Riyam
Photo by CardMapr on Unsplash
Text("Something cool goes in here.")
.font(.body)

SwiftUI provides us with an environment ContentSizeCategory. Here’s an example from my app where I change the layout from a grid to a list when the size increases:

struct HomeGameTypeView: View {
@EnvironmentObject var preferences: Preferences

@Environment(.sizeCategory) private var category

var body: some View {
if category >= .extraExtraLarge {
ScrollView {
LazyVStack {
list
}
}
} else {
LazyVGrid(columns: [.init(), .init()]) {
list
}
}
}

var list: some View {
ForEach(GameTypeOption.allCases) { type in
HomeGameTypeRow(selection: $preferences.gameTypeSelection, type: type)
}
}
}

In iOS 15, the ContentSizeCategory is deprecated and replaced by DynamicTypeSize. Rewriting the above example:

struct HomeGameTypeView: View {
@EnvironmentObject var preferences: Preferences

@Environment(.dynamicTypeSize) var size // <- NEW

var body: some View {
if size >= .xxLarge { // <- NEW
ScrollView {
LazyVStack {
list
}
}
} else {
LazyVGrid(columns: [.init(), .init()]) {
list
}
}
}
}

var content: some View {
Text(item.name.uppercased())
.font(.title)
.dynamicTypeSize(..<DynamicTypeSize.accessibility1) // <- RANGE
.foregroundColor(.primary)
}

To test different sizes in previews, you can add a constant size as an environment to the preview:

struct IntroductionView_Previews: PreviewProvider {
static var previews: some View {
IntroductionView()
.environment(.dynamicTypeSize, .accessibility1) // <- CONSTANT
}
}

If you’re constraining the text size, you can add the method accessibilityShowsLargeContentViewer(). When the user is on an accessibility text size, a long tap on the view shows an enlarged text size:

var body: some View {
Button(action: action) {
content
}
.buttonStyle(HomeButtonStyle(isSelected: false))
.padding([.bottom, .horizontal], 8)
.accessibilityShowsLargeContentViewer()
}

Dynamic Type helps your users use your app for any text size, providing them with an exceptional experience. Using SwiftUI makes it easier to add Dynamic Type and structure the views accordingly.

Want to Connect?If you have a better approach, let me know on Twitter!

Leave a Comment